When accepting PIDs as input, is there any sane validation that can take place? When accepting PIDs as input, is there any sane validation that can take place? unix unix

When accepting PIDs as input, is there any sane validation that can take place?


If you're on Linux, you can try doing a access("/proc/$PID/").Or more generally, you can do a kill(pid, 0) as explained in this answer to see if the process exists.

Of course, whatever you do, a syscall will be involved


Try the kill() function, with a signal of zero.Here's a snippet from the man page for kill() on Ubuntu:

int kill(pid_t pid, int sig);

If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.


Why? Stop second guessing users. The kernel will do all sanity checking for you. That is the most valid input validation for a PID - is the operation I'm trying to do successful. 0 is a valid number for a PID in certain situations. So are negative numbers.

If your code runs as a privileged process and you're trying to limit the damage it can do, then you'd need some serious validation rather than "sanity checking". But if it doesn't then there no reason for you to do anything. "No such process" is a good enough error message.