pcntl_fork and the MySQL connection is gone

Viewed 12684

I have a foreach loop that forks within it. After the process forks, it accesses the database. I get an error:

SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

The thing is, I'm connecting to the database after I've forked.

My question: Why would this be happening?

If this happens, am I actually accessing the database before forking? Will the child inherit DB connections?

(note: I can post code, but it's rather large as it's all in classes, which could be what is causing my confusion of when I'm accessing the DB. Another thing you should know is I'm using ZF.)

5 Answers

You need to close the MySQL connection on your parent process and then make a new connection for each child.

<?php
$dbh = new PDO('pgsql:host=localhost', $username, $password);
$pid = pcntl_fork();
if(!$pid){
        // make new connection
        $newConnection = new PDO('pgsql:host=localhost', $username, $password);
        // do something in the child process.
        exit;
}else{ 
        // parent node
        $dbh = null; // close PDO connection
}
Related