Process Management – Avoid Killing Wrong Process Using PID

killprocess

I do start a long-running background process within a Bash script. I save the PID number inside a variable after sending the process to background and I use that PID number to kill that process when necessary.

However, if that background process terminates somehow before my script kills it and system assigns the same PID number to a newly created process, when I use that number to kill that background process, this action would probably kill that newly created process (depending on permissions, of course).

A used PID number would not be assigned to any newly created process in a short time, I'm aware of that, but my script is running for weeks, so it's possible.

How can I prevent such an accident from happening?

Best Answer

There's no reliable way to do that.

Since PIDs are global, reusable IDs, using them is inherently racy. But the way the shells are implemented makes it much worse: a shell is reaping its children greedily, i.e. it calls the waitpid() system call as soon as they have died, and stores their PIDs and status somewhere in the memory. The background tasks started as foo & do NOT linger as zombie processes until you call the wait builtin command. A PID could've been already reused since you retrieved it with the jobs or pgrep commands.

Your best hope is to reduce the time window in which the PIDs could be reused, and minimize the risks. As suggested, you can use pkill instead of killing by PID explicitly. Especially useful is its -P flag ("select by parent"), thence

pkill -P "$$"
Related Question