> > > Here's pseudo code for what I'm trying to do: > > > > foreach ($things as $thing) { > > info = getInfo($thing); // uses a db connection > > makeApiCall(info); > > } > > > > makeApiCall(info) { > > $pid = pcntl_fork(); > > if ($pid == -1) { > > die("could not fork"); > > } else if ($pid) { > > // parent, return the child pid > > echo "child pid $pid\n"; > > return; > > } else { > > // do some api calls > > exit; > > } > > } > > > > But after I spawn off the process, getInfo($thing) errors out sometime > > later on with an "invalid query" error, because I think the db > > connection is gone. I thought adding "exit" in the child process > > would be enough, but that doesn't seem to work, I still get the same > > error. Why would the child process affect the query in the parent > > process, especially if I exit in the child process? > > First things first - I would add a pcntl_wait like this: > > foreach ($things as $thing) { > info = getInfo($thing); // uses a db connection > makeApiCall(info); > switch( $p=pcntl_wait( $stat, WNOHANG ) ) > { > case -1: echo "some sort of error in pcntl_wait()\n"; break; > case 0: break; > default: > echo "child $p finished\n"; > } > } > I actually tried this in the meantime: $pid = pcntl_fork(); if ($pid == -1) { die("could not fork"); } else if ($pid) { // parent, return the child pid echo "child pid $pid waiting\n"; pcntl_waitpid($pid, $status); if (pcntl_wifexited($status)) { echo "finished [$status] waiting\n"; return; } else { echo "ERROR\n"; } But it still has the same problem, and I'm also trying to avoid pcntl_wait or pcntl_waitpid at all because I still want to do it asynchronously. I even tried rewriting it do return $pid in the parent thread, and then aggregate them at the calling function level, and then loop through them all with pcntl_waitpid, but that didn't work either. > > > Second, it sounds like you're expecting to reuse your database > connection from getInfo() in the child you're forking in makeAPIcall()? > I don't think that really works - I think you need a new connection per > child. > Oh, in this case, I don't do anything with the database at all in the child thread. I was worried there would be some errors there so I actually commented out all db accesses in the child thread, but it still somehow closes the parent's db connection (or at least causes the query not to work, somehow).