Search code examples
phpmysqlmultiprocessingpcntl

How to use php pcntl_fork to run function in background


I have two functions. One function I want to run in the background with the mysql connection and without returning any errors or anything to the browser. And another function I want to run which returns data to the browser.

I've used the php pcntl_fork as follows:

$pid = pcntl_fork();
switch ($pid) {
  case -1:
    $this->function_background();
    $this->function_return();
    exit();
  case 0:
    $this->function_background();
    break;
  default:
    $this->function_return();
}

In this case, it returns database error number 2006 which can only occur in function_background().

I want the function function_background() to run completely and independently in the background with the mysql connection and without disturbing the browser with it's errors or anything. And function_return() for a message to the browser.

Appreciate any help. Great if anyone could please point me to detailed info as well.

Thanks.


Solution

  • As in the comment the pcnt_fork() is used for fork an existing process, for running it in background you could simply implement something using:

    $pid = shell_exec(sprintf('%s > /dev/null 2>&1 &', $command));
    

    where:

    • > /dev/null means that the stdout will be discarded;
    • 2>&1 means that the stderr will be on the stdout (so discarded);
    • & allows to run this command as a background task.

    and for check that the process is running

    $procResult = shell_exec(sprintf('ps %d', $pid));
    if (count(preg_split("/\n/", $procResult)) > 2) {
    
        return true;
    }