title: How to test if calling process is a fork
body: <p>Is there a method or C api in Linux/POSIX to determine if the current process is a fork? I.e. if it has been created by calling <code>fork()</code> without a subsequent call to the <code>execve()</code> family?</p>
  
  <p>I do not control the code leading up to this point (it runs within a high-level language binding). I just need to know if the current process is running the top level program, or in a fork thereof. </p>
  
  <p>The best I have come up with is testing if the process has the same gid as it's parent:</p>
  
  <pre><code>int is_fork = getpgid(0) == getpgid(getppid());
  </code></pre>
  
  <p>However this only works if the parent has called <code>setpgid()</code> which apparently <code>execve()</code> does not do by default. So that results in a lot of false positives.</p>