I realize this problem is likely not an issue anymore, but I did not find the presented alternatives very appealing, while there were some suggestions that I found very good, but not explored in depth.
First. How are pids assigned?
Pids are generated incrementally, looping back. So for the pid to be reassigned, a good part of the pid-space must be traversed (depends on how many processes are running).
This, at least, gives a bit of breathing time.
https://www.baeldung.com/linux/process-id
Second. If there is a really long time between querying the pid and killing it, AND there is sufficient process creation activity on the system compared to this gap in time, it is plausible, that the pid could have died and reused.
While I don't know of any atomic "search and kill" operation, the fact that pids are assigned in order gives a little breathing space.
Your best bet is to query if the process is still the same? For that, you can:
- add artificial markers to the command line, like some suggested
- use
pkill --pid $MYPID --pgroup $MYPGID
- use
pkill --pid $MYPID --parent $MYPARENT
-> this is my choice
Managing artificial markers is an extra hassle in my view, but using a UUID is probably the safest.
The process group ID may not exist, but a pretty good bet, although it may contain too many processes, especially if there are many backgrounded payload processes.
Since the backgrounded process is started from a parent script, the parent pid is a given. There is a chance that after loopback, the same parentpid-pid pair comes up, but the chances are pretty slim. Just for a very rough estimate, probably on the order of 1/65535/65535, that is about every 7 years, if a process is created every millisecond. With a lot of machines running for a long time, this is not a good solution. But it really depends on how the parent process behaves, if it stays around, and spawns a ton of new processes, the numbers can be very different.
kill PID
, just try the more explicitpkill <name>
command. Would this solve your problem?/proc/PID/environ
, or maybe just checking/proc/PID/exe
is sufficient?