brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: kill -0 checks whether a Linux process is still alive without touching it

Linux
~/tips/tip-linux-kill-0-is-process-alive

if kill -0 "$pid" 2>/dev/null; then

Test from a script whether a PID still exists before you wait for it or start a new copy.

Signal 0 is not really a signal. The kernel does all the checks for sending one, then sends nothing, which makes it a neat way to ask whether a process exists.

if kill -0 "$pid" 2>/dev/null; then
  echo "still running"
fi

The kill(2) man page puts it this way: if the signal number is 0, no signal is sent, but existence and permission checks are still performed. So the exit code is 0 when the process is there and you are allowed to signal it, and 1 when it is gone.

I find it handy with PID files, to tell a stale file from a real running process:

pid=$(cat /run/myjob.pid)
kill -0 "$pid" 2>/dev/null || rm -f /run/myjob.pid

The 2>/dev/null hides the No such process message for the normal case where it has stopped.

There are two traps. A process that belongs to another user gives a non zero exit too, with Operation not permitted, so as a normal user you cannot tell “gone” from “not yours”. Run as root, or look at /proc/$pid instead. And PIDs get reused: after a crash and a few hours, the number in an old PID file can belong to a completely different program. Check the name too, with ps -p "$pid" -o comm=, before you trust it.

Further reading: kill(2) manual page, kill(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link