As you all know, when you play a child, he gets a copy of everything, including file and network descriptors - man fork .
In PHP, when you use pcntl_fork, all your connections created using mysql_connect are copied, and this is a bit of a problem - php docs and Question SO . Common sense in this situation says to close the parent connection, create a new one and allow the child to use the old one. But what if this parent needs to create many children in a few seconds? In this case, you will create loads of new connections - one for each group of plugs.
What does this mean in code:
while (42) { $db = mysql_connect($host, $user, $pass); // do some stuff with $db // ... foreach ($jobs as $job) { if (($pid = pcntl_fork()) == -1) { continue; } else if ($pid) { continue; } fork_for_job($job); } mysql_close($db); wait_children(); sleep(5); } function fork_for_job($job) { // do something. // does not use the global $db // ... exit(0); }
Well, I don't want to do this - there are too many database connections. Ideally, I would like to be able to achieve this behavior:
$db = mysql_connect($host, $user, $pass); while (42) { // do some stuff with $db // ... foreach ($jobs as $job) { if (($pid = pcntl_fork()) == -1) { continue; } else if ($pid) { continue; } fork_for_job($job); } wait_children(); sleep(5); } function fork_for_job($job) { // do something // does not use the global $db // ... exit(0); }
Do you think this is possible?
Some other things:
- This is php-cli script
I tried using mysql_pconnect in the first example, but as far as I can tell, there is no difference - the mysql server receives so many new connections. Maybe because this cli and pconnect do not work, as in mod_php. As Mark noted, pconnect in php-cli makes no sense.
source share