[buug] checking a pid

Sean Neakums sneakums at zork.net
Thu Feb 27 03:05:01 PST 2003


commence  Ian Zimmerman quotation:

> How does one check in general if a number is a pid of a living
> process, under BSD?  The old saw kill(pid, 0) only works for my own
> processes - it will fail for other users' processes whether or not pid
> is alive.

But if kill returns non-zero, and the process exists and is not owned
by you, errno will be set to EPERM, whereas if the process does not
exist errno will be set to ESRCH.  So it is still possible to use this
method to check for the existence of a process, regardless of its
owner.

For example:

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>

int
main (int argc, char* argv[])
{
  int pid = atoi (argv[1]);
  if ((kill (pid, 0) == 0) || (errno == EPERM)) {
    printf ("Yes.\n");
  } else {
    printf ("No.\n");
  }
  exit (0);
}

-- 
 /                          |
[|] Sean Neakums            | Size *does* matter.
[|] <sneakums at zork.net>     | That's why I use Emacs.
 \                          |



More information about the buug mailing list