Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload