title: How do I keep my mysql connection in the parent process after pcntl_fork?
body: <p>As all of you know when you fork the child gets a copy of everything, including file and network descriptors - <code>man fork</code>.</p>
  
  <p>In PHP, when you use pcntl_fork all of your connections created with mysql_connect are copied and this is somewhat of a problem - <a href="http://php.net/manual/en/function.pcntl-fork.php#70721" rel="nofollow noreferrer">php docs</a> and <a href="https://stackoverflow.com/questions/3668615/pcntl-fork-and-the-mysql-connection-is-gone">SO question</a>. Common sense in this situation says close the parent connection, create new and let the child use the old one. But what if said parent needs create many children ever few seconds? In that case you end up creating <strong>loads</strong> of new connections - one for every bunch of forks.</p>
  
  <p>What does that mean in code:</p>
  
  <pre><code>while (42) {
  
    $db = mysql_connect($host, $user, $pass);
  
    // do some stuff with $db
    // ...
  
    foreach ($jobs as $job) {
          if (($pid = pcntl_fork()) == -1) {
              continue;
          } else if ($pid) {
              continue;
          }
      fork_for_job($job);
    }
  
    mysql_close($db);
    wait_children();
    sleep(5);
  }
  
  function fork_for_job($job) {
  
    // do something. 
    // does not use the global $db 
    // ...
  
    exit(0);
  }
  </code></pre>
  
  <p>Well, I do not want to do that - thats way too many connections to the database. Ideally I would want to be able to achieve behaviour similar to this one: </p>
  
  <pre><code>$db = mysql_connect($host, $user, $pass);
  
  while (42) {
  
    // do some stuff with $db
    // ...
  
    foreach ($jobs as $job) {
          if (($pid = pcntl_fork()) == -1) {
              continue;
          } else if ($pid) {
              continue;
          }
      fork_for_job($job);
    }
  
    wait_children();
    sleep(5);
  }
  
  function fork_for_job($job) {
  
    // do something
    // does not use the global $db 
    // ...
  
    exit(0);
  }
  </code></pre>
  
  <p>Do you think it is possible?</p>
  
  <p>Some other things:</p>
  
  <ul>
  <li>This is php-cli script</li>
  <li><strike>I've tried using mysql_pconnect in the first example but as far as I can tell there is no difference - the mysql server receives as much new connections. Maybe that's because it is cli and pconnect does not work as it was in mod_php.</strike> As Marc has noticed - pconnect in php-cli does not make sense.</li>
  </ul>