Skip to content

Instantly share code, notes, and snippets.

@shellus
Created September 29, 2017 01:31
Show Gist options
  • Select an option

  • Save shellus/d3341a2bf83a77d1860280923ee3814e to your computer and use it in GitHub Desktop.

Select an option

Save shellus/d3341a2bf83a77d1860280923ee3814e to your computer and use it in GitHub Desktop.

Revisions

  1. 娃娃脾气 created this gist Sep 29, 2017.
    69 changes: 69 additions & 0 deletions pcntl_fork_test.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    <?php
    /**
    * Created by PhpStorm.
    * User: shellus-in
    * Date: 2017/9/28
    * Time: 17:50
    */

    class Test
    {
    protected $lockPath;
    protected $doUnLock = false;
    public function __destruct()
    {
    if ($this->doUnLock){
    @unlink($this->lockPath);
    }
    }

    public function __construct($filename)
    {
    $this->lockPath = $filename;

    if (file_exists($this->lockPath)){
    var_dump("err: lock exists");
    exit(1);
    }
    file_put_contents($this->lockPath, "running");
    $this->doUnLock=true;
    $this->work();
    }

    protected function work(){
    var_dump("debug: child precess working");
    die(0);
    }
    }

    if (!isset($argv[1])){
    var_dump("err: args invalid");
    exit(1);
    }
    $lockPath = $argv[1];

    foreach (range(1,10) as $i){
    $pid = pcntl_fork();
    if ($pid === -1){
    var_dump("err: fork fail");
    exit(1);
    }

    if ($pid===0){
    var_dump("debug: precess id [$i] start");
    $instance = new Test($lockPath);
    unset($instance);
    exit(0);
    }else{
    pcntl_waitpid($pid, $status);
    $exitCode = pcntl_wexitstatus($status);
    var_dump("debug: precess id [$i] stop");

    if ($exitCode !== 0){
    break;
    }

    }
    }

    var_dump("debug: master precess done.");