Forking and MySQL connections

For some of our long-running processes we use PHP. It makes total sense from our perspective, because we can re-use all our existing business logic from our main PHP web application.

To make things more efficient, I recently started some work on using forks and have a couple of worker processes around.

This application is essentially the core of our transcoder. The parent process would retrieve new jobs from the queue and fire up a number of workers to actually transcode the file. The main problem is that the parent opens up a MySQL connection and fires off some queries. After the child process is done, it actually closes the MySQL connection regardless of if it was actually used or not.

This means I'll have to close all mysql connections before forking, and re-connecting right after. No big deal, but still at least a bit annoying.

<?php

$db = new MySQLi('hostname','user','password');

if (pcntl_fork()) {

    $status = 0;
    // parent
    pcntl_wait($status);

   $result = $db->query('select version()');
   if ($db->error) echo $db->error;

} else {

   // the child process does nothing and exits gracefully

}

?>

Output:

MySQL server has gone away