title: Using fork() and exec() to execute Python code from C++
body: <p>I am trying to use exec() to run Python from C++, and use pipes to communicate between the processes. I found that the C++ process keep waiting at the exec() command after the Python process terminates, which makes it unable to execute the codes below that line.</p>
  <p>Please check my code below (I have minimized the problem so the acutal communication part is removed)</p>
  <p>C++ file:</p>
  <pre><code>int main()
  {
      int pipe_cpp_to_py[2];
      int pipe_py_to_cpp[2];
      if (pipe(pipe_cpp_to_py) || pipe(pipe_py_to_cpp))
      {
          std::cout &lt;&lt; &quot;Couldn't open pipes&quot; &lt;&lt; std::endl;
          exit(1);
      }
      pid_t pid = fork(); 
      if (pid == 0)
      {
          std::cout&lt;&lt;&quot;child started&quot;&lt;&lt;std::endl;
          char *intrepreter=&quot;python3&quot;; 
          char *pythonPath=&quot;./Pipetest.py&quot;; 
          char *pythonArgs[]={intrepreter,pythonPath,NULL};
          std::cout&lt;&lt;&quot;child before exec&quot;&lt;&lt;std::endl;
          execvp(intrepreter,pythonArgs);
          std::cout&lt;&lt;&quot;child after exec&quot;&lt;&lt;std::endl;
          close(pipe_py_to_cpp[0]);
          close(pipe_cpp_to_py[1]);
          close(pipe_py_to_cpp[1]);
          close(pipe_cpp_to_py[0]);
          std::cout&lt;&lt;&quot;child terminated&quot;&lt;&lt;std::endl;
      }
      else if (pid &lt; 0)
      {
          std::cout &lt;&lt; &quot;Fork failed.&quot; &lt;&lt; std::endl;
          exit(1);
      }
      else
      {
          std::cout&lt;&lt;&quot;parent started&quot;&lt;&lt;std::endl;
          std::cout&lt;&lt;&quot;parent terminated&quot;&lt;&lt;std::endl;
          exit(0);
      }
      std::cout&lt;&lt;&quot;cpp terminated&quot;&lt;&lt;std::endl;
      return 0;
  }
  </code></pre>
  <p>Python file:</p>
  <pre><code>import os  
  import time
  import struct
      
  if __name__ == &quot;__main__&quot;:
      print(&quot;in python&quot;)
      exit()
  </code></pre>
  <p>Output:</p>
  <pre><code>ece:~/cpp&gt; ./Pipetest
  parent started
  parent terminated
  child started
  child before exec
  ece:~/cpp&gt; in python
  (blinking cursor here)
  </code></pre>
  <p>For the C++ file, if I remove the fork command and simply call exec() in the main function to execute the Python program, it will behave as expected and terminate successfully. Could anyone tell me what is going on?</p>
  <p>Update: Thanks for all the answers! Now I see that codes after exec() will not be executed. However, the output still confuses me because the new command prompt does not show up (in my case, it's ece:~/cpp&gt;). In fact, it shows up only after I enter something. This happens even when I replace exec() with system(). Why is this happening?</p>