使用proc_open安全地终止进程

时间:2016-03-24 03:14:42

标签: php proc-open

使用proc_open启动PHP内置服务器之后,我似乎无法杀死它。

$this->process = proc_open("php -S localhost:8000 -t $docRoot", $descriptorSpec, $pipes);
// stuff
proc_terminate($this->process);

服务器正在运行,但它并不想关闭该进程。我也试过了:

$status = proc_get_status($this->process);
posix_kill($status['pid'], SIGTERM);
proc_close($this->process);

我也尝过SIGINTSIGSTOP ...不要使用SIGSTOP

is a solution使用ps,但我喜欢以保持操作系统独立。

完整代码:

class SimpleServer
{

    const STDIN = 0;
    const STDOUT = 1;
    const STDERR = 2;

    /**
     * @var resource
     */
    protected $process;

    /**
     * @var []
     */
    protected $pipes;

    /**
     * SimpleAyeAyeServer constructor.
     * @param string $docRoot
     */
    public function __construct($docRoot)
    {
        $docRoot = realpath($docRoot);

        $descriptorSpec = [
            static::STDIN  => ["pipe", "r"],
            static::STDOUT => ["pipe", "w"],
            static::STDERR => ["pipe", "w"],
        ];
        $pipes = [];

        $this->process = proc_open("php -S localhost:8000 -t $docRoot", $descriptorSpec, $pipes);

        // Give it a second and see if it worked
        sleep(1);
        $status = proc_get_status($this->process);
        if(!$status['running']){
            throw new \RuntimeException('Server failed to start: '.stream_get_contents($pipes[static::STDERR]));
        }
    }

    /**
     * Deconstructor
     */
    public function __destruct()
    {
        $status = proc_get_status($this->process);
        posix_kill($status['pid'], SIGSTOP);
        proc_close($this->process);
    }
}

1 个答案:

答案 0 :(得分:0)

使用proc_terminate

杀死proc_open()

开始的进程是正确的功能

proc_terminate($status['pid'], 9);