Killing processes opened with popen()?

2019-01-26 11:50发布

I'm opening a long-running process with popen(). For debugging, I'd like to terminate the process before it has completed. Calling pclose() just blocks until the child completes.

How can I kill the process? I don't see any easy way to get the pid out of the resource that popen() returns so that I can send it a signal.

I suppose I could do something kludgey and try to fudge the pid into the output using some sort of command-line hackery...

3条回答
\"骚年 ilove
2楼-- · 2019-01-26 11:54

You can find the pid, and checks that you're really its parent by doing:

// Find child processes according to current pid
$res = trim(exec('ps -eo pid,ppid |grep "'.getmypid().'" |head -n2 |tail -n1'));
if (preg_match('~^(\d+)\s+(\d+)$~', $res, $pid) !== 0 && (int) $pid[2] === getmypid())
{
    // I'm the parent PID, just send a KILL
    posix_kill((int) $pid[1], 9);
}

It's working quite well on a fast-cgi PHP server.

查看更多
闹够了就滚
3楼-- · 2019-01-26 12:12

Well, landed on a solution: I switched back to proc_open() instead of popen(). Then it's as simple as:

$s = proc_get_status($p);
posix_kill($s['pid'], SIGKILL);
proc_close($p);
查看更多
乱世女痞
4楼-- · 2019-01-26 12:18

Just send a kill (or abort) signal using kill function:

查看更多
登录 后发表回答