note 70721 modified in function.pcntl-fork by danbrown
| From: | danbrown@php.net | Date: | Tue, 10 Aug 2010 15:46:45 +0000 |
| Subject: | note 70721 modified in function.pcntl-fork by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-171540@lists.php.net to get a copy of this message | ||
The reason for the MySQL "Lost Connection during query" issue when forking is the fact
that the child process inherits the parent's database connection. When the child exits, the
connection is closed. If the parent is performing a query at this very moment, it is doing it on an
already closed connection, hence the error.
An easy way to avoid this is to create a new database connection in parent immediately after
forking. Don't forget to force a new connection by passing true in the 4th argument of
mysql_connect():
<?php
// Create the MySQL connection
$db = mysql_connect($server, $username, $password);
$pid = pcntl_fork();
if ( $pid == -1 ) {
// Fork failed
exit(1);
} else if ( $pid ) {
// We are the parent
// Can no longer use $db because it will be closed by the child
// Instead, make a new MySQL connection for ourselves to work with
$db = mysql_connect($server, $username, $password, true);
} else {
// We are the child
// Do something with the inherited connection here
// It will get closed upon exit
exit(0);
?>
This way, the child will inherit the old connection, will work on it and will close upon exit. The
parent won't care, because it will open a new connection for itself immediately after forking.
Hope this helps.
--was--
The reason for the MySQL "Lost Connection during query" issue when forking is the fact
that the child process inherits the parent's database connection. When the child exits, the
connection is closed. If the parent is performing a query at this very moment, it is doing it on an
already closed connection, hence the error.
An easy way to avoid this is to create a new database connection in parent immediately after
forking. Don't forget to force a new connection by passing true in the 4th argument of
mysql_connect():
<?
// Create the MySQL connection
$db = mysql_connect($server, $username, $password);
$pid = pcntl_fork();
if ( $pid == -1 ) {
// Fork failed
exit(1);
} else if ( $pid ) {
// We are the parent
// Can no longer use $db because it will be closed by the child
// Instead, make a new MySQL connection for ourselves to work with
$db = mysql_connect($server, $username, $password, true);
} else {
// We are the child
// Do something with the inherited connection here
// It will get closed upon exit
exit(0);
?>
This way, the child will inherit the old connection, will work on it and will close upon exit. The
parent won't care, because it will open a new connection for itself immediately after forking.
Hope this helps.
http://php.net/manual/en/function.pcntl-fork.php