Yii Framework Forum: Pcntl_fork, MySQL and Yii - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Pcntl_fork, MySQL and Yii

#1 User is offline   Lucas 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 20
  • Joined: 04-June 09

Posted 28 July 2009 - 03:08 AM

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 :)
1

#2 User is offline   huggie 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 03-August 09
  • Location:The Netherlands

Posted 28 August 2009 - 04:07 PM

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);

0

#3 User is offline   Nathan Phan 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 8
  • Joined: 10-October 12

Posted 16 September 2015 - 12:35 AM

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?
0

#4 User is offline   rincewind 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 5
  • Joined: 12-November 12

Posted 09 November 2015 - 10:23 PM

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
1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users