How to kill all processes except PID 1

killprocess

I want to kill all processes on a system except for PID 1.

I am currently using pgrep -l . | awk "{if (\$1 != 1) print \$1}" | xargs -n 1 kill -s INT.

awk is used to exclude the process with PID 1

If I run the command on alpine linux (which uses sh), I get:

# pgrep -l . | awk "{if (\$1 != 1) print \$1}" | xargs -n 1 kill -s INT
kill: can't kill pid 265: No such process

I believe PID 256 is from awk.

Is there a clean way (using utilities that should be available across most linux systems) to kill all processes except for PID 1?

Best Answer

On Linux at least,

kill -- -1

Will send the SIGTERM signal to every process it can except for the calling process (so the process running that kill command which could be the shell if kill is built-in there (it usually is on POSIX shells) or the process running a standalone kill command) and the process of pid 1.

Note that it does it as part of the kill() system call, so it's more reliable than using commands like pkill or killall (or the traditional killall command sometimes found as killall5 on Linux traditionally used for that) that first list the processes and then kill them as those would miss the processes that have been spawned in the mean time.

So it sounds like exactly what you want.

trap '' TERM # ignore SIGTERM ourselves though it wouldn't be needed 
             # in most shells
kill -- -1
sleep 1 # leave processes some time to exit cleanly on SIGTERM
kill -s KILL -- -1 # removes the remaining processes or those 
                   # that have started since without giving them
                   # a chance to clean-up.
exit

Should kill everything but the process of id 1.

You can experiment with it by running:

unshare --mount-proc -mpf

That starts a shell in a separate pid and mount namespace (with a new /proc (as used by ps/pkill/killall)) where that shell has pid 1.

Outside of Linux, kill -- -1 should work on every system at killing most processes, but the list of processes that are exempt from the killing can vary from system to system.

Related Question