How does one determine the file that represents the current process' executable?
The problem is that argv[0]
is not reliable, as if it was called via execXp
, the path entry that satisfied a non-qualified command may or may not be prepended. Furthermore, ANY caller to exec*
can replace argv[0]
with ANYTHING.
Hence, if you run ps
, you are not guaranteed that argv[0]
will be "/usr/bin/ps"
. In fact, you're probably guaranteed the OPPOSITE.
I need one of the following:
- the full path name (without doing a path search myself, lest the envp I am using is not the one the shell used)
- a live, pre-opened file descriptor to the file that corresponds to the current process' image
- some magic descriptor that corresponds to the code segment currently in memory (not quite sure about the BSS segment, though)
In this way, at startup I can quickly open an FD to my own executable (for case 1., in case the file gets removed and becomes unopenable), and then at a much later date call:
int fexecve(int fd, char *const argv[], char *const envp[]);
to fork
/exec
myself (typically needed on OS-X to work around the unreliability of the global and system descriptor state after fork()
). In other words (this example is silly, of course):
void magicallyReplicate(argc, argv)
{
if (!fork()) {
magicallyExecMyself(argc, argv);
}
}
or even just:
void startOver(argc, argv)
{
magicallyExecMyself(argc, argv);
}
Of course, in my example, I will be using different argv
's so that I can run in a different mode.
(early "no" retort: you can't use clone()
, as it is of fork()
's lineage)