How can I find a process' executable file?

How can I find a process' executable file?


This would be a good candidate for a list of `Frequently Unanswered
Questions', because the fact of asking the question usually means that
the design of the program is flawed. :-)



You can make a `best guess' by looking at the value of argv[0].
If this contains a `/', then it is probably the absolute or
relative (to the current directory at program start) path of the
executable. If it does not, then you can mimic the shell's search of
the PATH variable, looking for the program. However, success is
not guaranteed, since it is possible to invoke programs with arbitrary
values of argv[0], and in any case the executable may have been
renamed or deleted since it was started.



If all you want is to be able to print an appropriate invocation name
with error messages, then the best approach is to have main()
save the value of argv[0] in a global variable for use by the
entire program. While there is no guarantee whatsoever that the value
in argv[0] will be meaningful, it is the best option available in
most circumstances.



The most common reason people ask this question is in order to locate
configuration files with their program. This is considered to be bad
form; directories containing executables should contain nothing
except executables, and administrative requirements often make it
desirable for configuration files to be located on different filesystems
to executables.



A less common, but more legitimate, reason to do this is to allow the
program to call exec() on itself; this is a method used
(e.g. by some versions of sendmail) to completely reinitialise
the process (e.g. if a daemon receives a SIGHUP).






Home FAQ