Comos\Qpm\Process\Process::fork PHP Method

fork() public static method

public static fork ( Comos\Qpm\Process\Runnable | Callable $target ) : Comos\Qpm\Process\ChildProcess
$target Comos\Qpm\Process\Runnable | Callable
return Comos\Qpm\Process\ChildProcess
    public static function fork($target)
    {
        if (!\is_callable($target) && !$target instanceof Runnable) {
            throw new \InvalidArgumentException('$target must be a valid callback or Comos\\Qpm\\Process\\Runnable');
        }
        $pid = \pcntl_fork();
        if ($pid == -1) {
            throw new FailToForkException('fail to folk.');
        }
        if ($pid == 0) {
            try {
                if ($target instanceof Runnable) {
                    $code = $target->run();
                } else {
                    $code = \call_user_func($target);
                }
            } catch (\Exception $ex) {
                Logger::err($ex);
                $code = -1;
            }
            if (\is_null($code)) {
                $code = 0;
            } elseif (!\is_int($code)) {
                $code = 1;
            }
            exit($code);
        }
        return new ChildProcess($pid, self::getCurrentPid());
    }

Usage Example

Example #1
0
 public function testStart_Start2ProcessWithOnePidFile()
 {
     $pidfile = $this->_pidFile;
     $process = \Comos\Qpm\Process\Process::fork(function () use($pidfile) {
         $man = new Manager($pidfile);
         $man->start();
         usleep(200 * 1000);
     });
     usleep(100 * 1000);
     $man1 = new Manager($pidfile);
     $process1 = $man1->getProcess();
     $this->assertTrue($process1 instanceof \Comos\Qpm\Process\Process);
     try {
         $man2 = new Manager($this->_pidFile);
         $man2->start();
         $this->fail('expects Exception');
     } catch (\Exception $e) {
         $st = 0;
         $pidfile = pcntl_wait($st);
         $this->assertEquals($pidfile, $process->getPid());
         $this->assertEquals($pidfile, $process1->getPid());
         $this->assertTrue(\pcntl_wifexited($st));
         $this->assertTrue($e instanceof \Comos\Qpm\Pid\Exception);
         $this->assertEquals('process exists, no need to start a new one', $e->getMessage());
     }
 }
All Usage Examples Of Comos\Qpm\Process\Process::fork