Pcntl_fork, MySQL and Yii

I’m writing a console application with Yii, and encountered the MySQL Server has gone away error. This is related to using PHP’s pcntl_fork(), which makes PHP lose its MySQL connection after a while in the child processes.

The Yii solution is very easy, but I thought I might share it anyway for people who’d encounter the same issue:


                    Yii::app()->getDb()->setActive(false);

                    $pid = pcntl_fork();

                    Yii::app()->getDb()->setActive(true);

This basically closes the connection before forking, and reinstantiates it in the child and parent after the fork. By doing that, the error disappears and you can continue to use everything you had already collected from the db :)

thanks for this piece of code. too bad my webhosting provider does not have the pcntl extension installed.

i fixed my ‘mysql server has gone away’ by adding these lines in front of all the queries;


Yii::app()->getDb()->setActive(false);

Yii::app()->getDb()->setActive(true);

Hi huggie

you said in front of all queries.

Does it mean that all Active record queries or queries created by createCommand()?

I am having the same problem with Mysql gone away. Wonder if yii has something called auto reconnect? or how to you guys overcome this problem?

The issue is that the child process inherits the database connection. The common practice is to reinitiate the database connection in the parent process after we forked off a child.




$pid = pcntl_fork();

if($pid == -1){

    //Problem launching the job

    die();

}

elseif ($pid){

    // Parent process


    // child inherits parents db connection so we have to reconnect

    $this->reconnect();


    //do whatever

}

else {

    //Forked child, do your deeds, database connection active

    

    // exec child code


    // finish

    exit();

}



However, this has nothing to do with yii, and you have to reconnect to the database