note 70721 added to function.pcntl-fork

From: Date: Wed, 25 Oct 2006 09:06:29 +0000
Subject: note 70721 added to function.pcntl-fork
Groups: php.notes 
Request: Send a blank email to php-notes+get-119092@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(): <? // 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. ---- Server IP: 195.248.191.91 Probable Submitter: 83.170.205.170 ---- Manual Page -- http://www.php.net/manual/en/function.pcntl-fork.php Edit -- https://master.php.net/note/edit/70721 Del: integrated -- https://master.php.net/note/delete/70721/integrated Del: useless -- https://master.php.net/note/delete/70721/useless Del: bad code -- https://master.php.net/note/delete/70721/bad+code Del: spam -- https://master.php.net/note/delete/70721/spam Del: non-english -- https://master.php.net/note/delete/70721/non-english Del: in docs -- https://master.php.net/note/delete/70721/in+docs Del: other reasons-- https://master.php.net/note/delete/70721 Reject -- https://master.php.net/note/reject/70721 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119092) next »