1

I have written a Zend Framework based cron service for parallel tasks based on these two blog articles:

In summary, the cron services uses pcntl_fork() to spawn the tasks in parallel.

Running a single task with the service works without issues, but when I add a second task, I get this MySQL error:

General error: 2006 MySQL server has gone away

My best guess is that a child thread ends before the other and the MySQL connection is implicitly closed. If this is the case, how do I ensure that the connection stays open until the parent thread closes?

Sonny
  • 8,204
  • 7
  • 63
  • 134
  • Connect to the database AFTER you fork(). If you connect before your fork, that connection is shared by the children and MySQL isn't set up for multiple processes sharing the same connection. – Marc B Jun 10 '11 at 17:27
  • The bootstrap process before the forking connects to the database, and necessarily so. I've been reading the comments on http://php.net/pcntl-fork and I am coming to the conclusion that I'll have to remove the forking. I hope there's another way. – Sonny Jun 10 '11 at 17:35
  • 1
    You can always have the children fire up a new connection. Just don't re-use any of the connections established by the parent. – Marc B Jun 10 '11 at 17:58
  • @Marc B - Thanks! I was typing up that very solution when you wrote your comment. – Sonny Jun 10 '11 at 18:07

1 Answers1

1

After reading the comments on pcntl_fork() and this SO question, it was indeed the issue with children sharing the parent connection. I have added this code to create a new MySQL connection after forking, and it seems to have fixed the problem:

// give this thread its own db connection
$settings = Zend_Registry::get('settings');
$db = Zend_Db::factory(
    $settings->db_adapter,
    array(
        'host' => $settings->db_host,
        'username' => $settings->db_user,
        'password' => $settings->db_pass,
        'dbname' => $settings->db_name,
    )
);
$db->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Db_Table::setDefaultAdapter($db);
Community
  • 1
  • 1
Sonny
  • 8,204
  • 7
  • 63
  • 134