note 77603 added to ref.pcntl
| From: | registrazioni at XSPAMX dot tassetti dot net | Date: | Wed, 05 Sep 2007 16:12:17 +0000 |
| Subject: | note 77603 added to ref.pcntl | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-130211@lists.php.net to get a copy of this message | ||
(PHP 5.2.4)
This is an example of multithreading keeping different connections to a mysql database: when
children exit they close the connection and others can't use it any more generating problems.
In this example I used variable variables to make a different connection per each child.
This scripts loops forever with one mother detached from the terminal and five children
'named' from 1 to 5. When one children sees it's name in the database (one table
'test.tb' with only one field 'test') he lets himself die. To kill children
insert their value in the db. The mother suicides only when all children are dead.
What a sad but interesting story...
$npid = pcntl_fork(); // DETACH FROM TERMINAL AND BE REAPED BY INIT
if ($npid==-1) die("Error: impossible to pcntl_fork()\n");
else if ($npid) exit(0); // THE GRANPA DIES
else // MOTHER GOES ON TO MAKE CHILDREN
{
$children = 5;
for ($i=1; $i<=$children; $i++)
{
$pid = pcntl_fork();
if ($pid==-1) die("Error: impossible to pcntl_fork()\n");
else if ($pid)
{
$pid_arr[$i] = $pid;
}
if (!$pid) // CHILDREN
{
global $vconn;
$vconn = "vconn$i";
global $$vconn;
$$vconn = @mysql_connect("mydbhost","mydbuser","mydbpwd");
if (!($$vconn)) echo mysql_error();
if (!($$vconn)) exit;
while (1)
{
$query = "SELECT test FROM test.tb";
$rs = mysql_query($query,$$vconn);
$rw = mysql_fetch_row($rs);
if ($rw[0]==$i) exit;
else
{
echo "Database is $rw[0] and I am $i, it's not my time, I will wait....\n";
sleep(1);
}
}
}
}
foreach ($pid_arr as $pid)
{
// we are the parent and we wait for all children to die
pcntl_waitpid($pid, $status);
}
echo "All my children died, I will suicide...\n";
exit();
}
----
Server IP: 80.241.173.254
Probable Submitter: 84.220.187.18
----
Manual Page -- http://www.php.net/manual/en/ref.pcntl.php
Edit -- https://master.php.net/note/edit/77603
Del: integrated -- https://master.php.net/note/delete/77603/integrated
Del: useless -- https://master.php.net/note/delete/77603/useless
Del: bad code -- https://master.php.net/note/delete/77603/bad+code
Del: spam -- https://master.php.net/note/delete/77603/spam
Del: non-english -- https://master.php.net/note/delete/77603/non-english
Del: in docs -- https://master.php.net/note/delete/77603/in+docs
Del: other reasons-- https://master.php.net/note/delete/77603
Reject -- https://master.php.net/note/reject/77603
Search -- https://master.php.net/manage/user-notes.php