title: Need PID of current process, getpid() returns -1
body: <p>I need to come up with a unique name for a file used by a process (executing my C++ program). Before I used a static string, but when I tried to run two instances of the program in parallel, I realized they were both accessing the same file.</p>
  
  <p>To this end, I would like the file name to include the PID of the process that creates and is using it.</p>
  
  <p>However, when I try to use <code>getpid()</code>, I always seem to get <code>-1</code> as the return value.</p>
  
  <pre><code>void accessfile(){
     std::cout &lt;&lt; "DEBUG: accessfile() called by process " &lt;&lt; getpid() &lt;&lt; " (parent: " &lt;&lt; getppid() &lt;&lt; ")" &lt;&lt; std::endl;
     // Code here to create and/or access the file
  }
  </code></pre>
  
  <p>When I run this, I get:</p>
  
  <pre><code>DEBUG: accessfile() called by process -1 (parent: 17565)
  </code></pre>
  
  <p>I checked <code>ps ux</code> and the process <code>17565</code> is actually my login shell. How do I get the PID of the program I'm currently executing?</p>
  
  <p>I did notice this bit of information in the manual entry for <code>getpid()</code>:</p>
  
  <pre><code>   Since glibc version 2.3.4, the glibc wrapper function for getpid()
     caches PIDs, so as to avoid additional system calls when a process
     calls getpid() repeatedly.  Normally this caching is invisible, but
     its correct operation relies on support in the wrapper functions for
     fork(2), vfork(2), and clone(2): if an application bypasses the glibc
     wrappers for these system calls by using syscall(2), then a call to
     getpid() in the child will return the wrong value (to be precise: it
     will return the PID of the parent process).  See also clone(2) for
     discussion of a case where getpid() may return the wrong value even
     when invoking clone(2) via the glibc wrapper function.
  </code></pre>
  
  <p>Indeed I am using glibc 2.4. I understand that using <code>getpid()</code> without a corresponding <code>fork()</code> may cause an issue, but I don't see the behavior they describe. <code>getppid()</code> correctly gets the parent PID (the login shell), but yet the return value of <code>getpid()</code> doesn't seem to make sense.</p>
  
  <p>Can anyone shed light on why it returns -1 (can't find any documentation that details what this return value means), and also how I might be able to get the process ID? Do I need to just fork a dummy process <em>just</em> to get the current process ID? Thanks!</p>