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
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.
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
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.