Kill all shared memory segments in Linux
Tags: Reading time: 2 minutes Suggest a change
I recently whipped up a shell script to kill all (IPC) shared memory segments in Linux for a client on oDesk. He wound up going with another contractor's offer, and so I figured I would post my script here for the benefit of all.
ipcs -m | cut -d' ' -f2 | grep '^[0-9]' | while read $x; do ipcrm -m $x; done
Here's what the individual pieces do:
- ipcs -m - This command lists all current shared memory segments. (Using -s would list semaphores, etc.)
- cut -d' ' -f2 - This command cuts 2nd column from the ipcs output, using spaces as its delineating mark.
- grep '^[0-9]' - This command only allows results which begin with a number to pass through. (We don't want the header output from ipcs to mess with our process.)
- while read $x… - This command iterates over the output from the previous commands—which, by this point, will be the identifying number belonging to each shared memory segment—and runs the ipcrm IPC removal command against that output.
If you've got an unruly list of shared memory segments on your Linux machine and you just want them all to go away, fret no longer!
This, for some reason, is one of my most popular blog posts. As such, I feel like it deserves an update now that I've leveled up a bit in my Linux usage. Here is a more succinct method that should be easier to understand and more universal:
for x in $(ipcs -m | awk 'NR>1 {print $2}'); do ipcrm -m $x; done
The differences are:
- awk 'NR>1 {print $2}' - This uses
awk
to print the 2nd column of each line of output, but only when the line number is greater than 1. This skips the first line of output containing the headers fromipcs
. Now we no longer needcut
norgrep
. - Instead of piping output to a while loop, the
$()
syntax is used inline as the argument of a for loop. Now we no longer needread
.
Cheers!
Posted: