title: Parent process exits twice using fork() execv() in c++
body: <p>I have a multiprocessing application that works well, except the parent process seems to exit twice.</p>
  <p>I left out some of the code for simplification. Basically, I use libcurl (I wrote my own abstraction layer for it) to get JSON data from a server (left the code for this out) and then the simdjson library to iterate through it and run worker processes where required.</p>
  <p>At the end I wait for all child processes (in the parent process) to terminate before printing &quot;done&quot;. I can see however, that my program is printing &quot;done&quot; twice. I presume once after it's done in the for loop to create all the worker processes and then again once the last child returns. At least that is what I can see from the output on the console, as the child processes print to the console as well. However, given that I use <code>if (pid_fork &gt; 0)</code>, i.e. I must be in the parent process, any subsequent code should be executed only once. What am I doing wrong?</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  
  #include &lt;sys/stat.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &quot;simdjson.h&quot;
  
  int main (int argc, char *argv[]) 
  {   
      /* some other code */
      
      pid_t pid_fork;
      std::vector&lt;int&gt; v_pid;
  
      // loop through json
      for (simdjson::dom::element mq_item : json_mq_items)
      {
          pid_fork = fork();
          if (pid_fork == -1)
          {
              std::cout &lt;&lt; &quot;error: could not fork process&quot; &lt;&lt; std::endl;
              return EXIT_FAILURE;
          } else if (pid_fork &gt; 1) // parent process
          {
              v_pid.push_back(pid_fork);
          }
          else // child process (pid_fork == 0)
          {
              char *argv[] = { (char*)(std::string(&quot;foo&quot;)), NULL };
              if (execv((static_cast&lt;std::string&gt;(&quot;./foo&quot;)).c_str(), argv) == -1)
              {
                  std::cout &lt;&lt; &quot;could not load child&quot; &lt;&lt; std::endl;
                  return EXIT_FAILURE;                    
              }
          }
      }
  
      // in parent process only
      if (pid_fork &gt; 0)
      {
          // Wait for all child processes to terminate
  
          for (size_t i = 0; i &lt; v_pid.size(); i++) 
          {
              while (waitpid(v_pid[i], NULL, 0) &gt; 0);
          }
  
          /* some other code */
  
          std::cout &lt;&lt; &quot;done&quot; &lt;&lt; std::endl;
  
          return EXIT_SUCCESS;
      }   
  }
  </code></pre>