title: Getting the actual process id of a command that is executed in background using C++
body: <p>Lets say i have run a simple background process which is:</p>
  
  <pre><code>sleep 25 &amp;
  </code></pre>
  
  <p>I execute it on the command line as :</p>
  
  <pre><code>&gt; sleep 25 &amp;
  [1] 26390
  &gt; ps
     PID TTY         TIME CMD
   26390 pts/52      0:00 sleep
    6746 pts/52      0:02 tcsh
   26391 pts/52      0:00 ps
  &gt; 
  </code></pre>
  
  <p>You can see that sleep is executing in the background with pid <code>26390</code>
  Now I try to do the same thing using c++.there are many different system calls to do it btw.</p>
  
  <pre><code>using system
  using fork
  using pipe
  </code></pre>
  
  <p>I tried below code:</p>
  
  <pre><code>if(p=fork()){
  //Main process
  cout&lt;&lt;p&lt;&lt;endl;
  }
  else{
  execv("sleep 20 &amp;",(char **)NULL);
  }
  }
  </code></pre>
  
  <p>output is:</p>
  
  <pre><code>&gt; ./a.out
  27391
  &gt; ps
     PID TTY         TIME CMD
    6746 pts/52      0:02 tcsh
   27392 pts/52      0:00 ps
  &gt; 
  </code></pre>
  
  <p>You can see that there is no sleep running in the background.
  Now i tried another way:</p>
  
  <pre><code>FILE* pipe = popen("sleep 20 &amp;", "r");
      if(pipe){
                  char buffer[128];
                  while(fgets(buffer, 128, pipe));
                  cout&lt;&lt;buffer&lt;&lt;endl;
                  pclose(pipe);
               }
  </code></pre>
  
  <p>This hangs for 20 seconds and i will never get that cout printed with the process id.</p>
  
  <pre><code>&gt; ./a.out
  
  &gt; 
  </code></pre>
  
  <p>Again I tried another way:</p>
  
  <pre><code>if(p=fork()){
  //Main process
  cout&lt;&lt;p&lt;&lt;endl;
  }
  else{
  system("sleep 20 &amp;");
  }
  }
  
  &gt; ./a.out
  27464
  &gt; ps
     PID TTY         TIME CMD
   27466 pts/52      0:00 sleep
   27467 pts/52      0:00 ps
    6746 pts/52      0:02 tcsh
  </code></pre>
  
  <p>Now you can see sleep running in the background but with different PID.</p>
  
  <p>But what i need is the actual pid of the sleep command that is executed in the background.
  I strongly believe that there should be some way to get the exact pid of the process running in the background in c++. Could anybody please help?</p>