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,
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 ifkill
is built-in there (it usually is on POSIX shells) or the process running a standalonekill
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 likepkill
orkillall
(or the traditionalkillall
command sometimes found askillall5
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.
Should kill everything but the process of id 1.
You can experiment with it by running:
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.