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.

  1. <?php
  2.  
  3. $db = new MySQLi('hostname','user','password');
  4.  
  5. if (pcntl_fork()) {
  6.  
  7. $status = 0;
  8. // parent
  9. pcntl_wait($status);
  10.  
  11. $result = $db->query('select version()');
  12. if ($db->error) echo $db->error;
  13.  
  14. } else {
  15.  
  16. // the child process does nothing and exits gracefully
  17.  
  18. }
  19.  
  20. ?>

Output:

  1. MySQL server has gone away
 1

About

My name is Evert, and I've been writing semi-regularly on this blog since 2006.

I'm currently available for contract work.

more info.

Subscribe

Dropbox

Dropbox is a simple cross-platform online backup and sync application. The first 2GB of space is free, and both you and me get an extra 250MB extra space if you sign up through this link.