title: pcntl_fork and then pcntl_exec or pcntl_exec and then pcntl_fork
body: <p><strong>Explanation:</strong>
  Part of the app that I'm creating requires checking of thousands of records and acting on them in a <em>timely</em> manner. So for every record, I want to fork a new process. However, I need a DB connection to do some more checking of that record. As I understand it, the child inherits the DB connection. So subsequent forks have DB errors.</p>
  
  <p>I thought I could pcntl_exec('php /path/script.php'); and then pcntl_fork so that the calling process is not held up.</p>
  
  <p>Or I can pcntl_fork and then pcntl_exec in the child process. Or maybe I should be using exec() instead of pcntl_exec().</p>
  
  <p><strong>My question:</strong> Are there any drawbacks or advantages to either order?</p>
  
  <p><strong>Notes:</strong>
  Maybe I'm imagining this issue, as I thought that the calling php process would wait for pcntl_exec to return. But that's not what the docs state:</p>
  
  <blockquote>
    <p>Returns FALSE on error and does not return on success.</p>
  </blockquote>
  
  <p>How can a function return a value sometimes and none other times? That sounds like poorly written docs.</p>
  
  <p>fahadsadah's comments state:</p>
  
  <blockquote>
    <p>Once the executed process ends, control returns to the webserver process.</p>
  </blockquote>
  
  <p>If that is the case, then I need to fork.</p>
  
  <p><strong>Edit: code for the confused - including me ;)</strong></p>
  
  <pre><code>&lt;?php
  
  class Process
  {
  
      public function __construct($arg = false)
      {
          if ($arg == "child")
          {
              $this-&gt;act();
          }
          else
          {
              $this-&gt;run();
          }
      }
  
      public function run()
      {
          echo "parent before fork:", getmypid(), PHP_EOL;
          $pid = @ pcntl_fork();
          echo $pid, PHP_EOL;
  
          if ($pid == -1)
          {
              throw new Exception(self::COULD_NOT_FORK);
          }
          if ($pid)
          {
          // parent
              echo "parent after fork:", getmypid(), PHP_EOL;
          }
          elseif ($pid == 0)
          {
          // child
              echo "child after fork:", getmypid(), PHP_EOL;
              //echo exec('php Process.php child');
              echo pcntl_exec('/usr/bin/php', array('Process.php', 'child'));
          }
          return 0;
      }
  
      private function act()
      {
          sleep(1);
          echo "forked child new process:", getmypid(), PHP_EOL;
          return 0;
      }
  }
  
  $proc = new Process($argv[1]);
  </code></pre>
  
  <p>If you uncomment the exec and comment the pcntl_exec, you will see that pcntl_exec replaces the process. Which I'm guessing saves some resources.</p>