Mysql with pcntl.... how?

I received the error message “MySQL server has gone away” with PCNTL/MySQL. It looks like MySQL has to be treated differently with PCNTL, but I don’t know exactly how to do it yet. Anyone have experience with this?

My code is something like this:


$S = mysql_query("SELECT * FROM Units LIMIT 6") or die(mysql_error());
while($S2 = mysql_fetch_assoc($S)) {
	$Units[] = $S2['ID'];
}


foreach($Units as $ID) {
	$pids[$ID] = pcntl_fork();
	if(!$pids[$ID]) {
		$Query2 = mysql_query("SELECT * FROM UnitData WHERE UnitID = '$ID'") or die();
		while($Return2 = mysql_fetch_assoc($Query2)) {
			// DO STUFF
		}
		file_get_contents('something');
		exit();
	}
}
		
foreach($Units as $ID) {
  pcntl_waitpid($pids[$ID], $status, WUNTRACED);
}

Can I ask…why are you using the old MySQL extension?

Umm, cause lol

mysql_* is not thread safe. Use pdo. Have each process open up its own connection as well

I found this post:

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.

the more apt approach would be to have the child invoke it’s own connection - if you ever have to fork more than once, the strategy outlined above will still run the problem of all children using a single connection. There will only be one parent. There can be many children.

Honestly, I don’t know enough to understand how it works, but I got my script going and oh my god it’s faster than I could have imagined. I’m shocked to be honest lol.