2

After starting a the PHP built in server with with proc_open, I seem to be unable to kill it.

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

The server is working, however it doesn't want to close the process. I've also tried:

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

I also tried SIGINT and SIGSTOP... don't use SIGSTOP.

There is a solution using ps however I would like to keep it OS independent.

Full code:

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);
    }
}
DanielM
  • 6,380
  • 2
  • 38
  • 57

1 Answers1

0

Use proc_terminate

It is the proper function to kill process started by proc_open()

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

Harikrishnan
  • 9,688
  • 11
  • 84
  • 127
  • 1
    `proc_terminate` was the first thing I tried (see above). I hadn't tried `SIGKILL` but even that doesn't seem to kill it. I'm wondering if it's some quirk of the PHP built in server. – DanielM Mar 24 '16 at 04:54