【问题标题】:Safely killing processes started with proc_open使用 proc_open 安全地杀死进程
【发布时间】:2016-03-24 03:14:42
【问题描述】:

使用 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);
    }
}

【问题讨论】:

    标签: php proc-open


    【解决方案1】:

    使用proc_terminate

    杀死proc_open()启动的进程是正确的函数

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

    【讨论】:

    • proc_terminate 是我尝试的第一件事(见上文)。我没有尝试过SIGKILL,但即使这样似乎也没有杀死它。我想知道这是否是 PHP 内置服务器的一些怪癖。
    猜你喜欢
    • 2013-01-12
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多