How to find process name in c?

Guy Harris guy at auspex.auspex.com
Sun Jul 15 12:59:38 AEST 1990


(Another one for the FAQ list?  Or is it already there?)

>Has anyone got a method for finding out if a process is running short of
>"ps -ef | grep processname" in a pipe.  There must be a better way from
>within a c program.

1) Processes in most UNIX systems don't have names, they have process
   IDs.  If you have 10 people on your machine running "cat", they are
   doing so in 10 distinct processes, but the "name" of those processes,
   as reported by "ps", will all be "cat".  If they gave the same
   arguments to "cat", the entire command line as reported by "ps"
   should be the same.

2) The innards of "ps" differ quite a bit from UNIX implementation to
   UNIX implementation - including potentially from version to version
   of any particular thread of UNIX implementations.  Some, but not all,
   provide programmatic interfaces to let you do some of what "ps" does;
   SunOS 4.x provides the "kvm" library, and some of the later S5
   releases, including S5R4, provide "/proc".

3) If you know the process ID of the process, you can, in most modern
   UNIX systems, determine whether a process with that process ID
   exists; use the "kill" call to send that process signal number 0. 
   This will not actually do anything *to* that process; however, it
   will do all the same checking that sending a real signal would do. 
   As such, if the "kill" fails, returning -1 and setting "errno" to
   ESRCH, you know no process with that process ID exists; if it
   succeeds, or fails with any other error (e.g. EPERM), you know it
   exists.

   One caveat: different flavors of UNIX report different things if the
   process has exited but the corpse hasn't yet been reaped by its
   parent.  As I remember, 4.2BSD and later indicate that it doesn't
   exist (I don't think 4.1BSD and earlier supported sending "signal
   0"), and S5 systems report that it does (I forget whether S3 had
   "signal 0", but I don't think it did).  POSIX appears to require the
   S5 behavior.

   Another caveat; I didn't say, in the first sentence of 3), "determine
   whether that process exists", I said "determine whether a process
   with that process ID exists".  Your process could have exited; if
   enough time had passed since it did, and enough other processes
   created new processes with by forking, some new process could be
   assigned the same process ID as the old process, giving you a "false
   positive".



More information about the Comp.unix.questions mailing list