Killing processes opened with popen()?

心已入冬 提交于 2019-11-28 03:34:55

问题


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...


回答1:


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);



回答2:


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

  • php http://php.net/manual/en/function.posix-kill.php
  • c/c++ http://linux.die.net/man/3/kill



回答3:


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.



来源:https://stackoverflow.com/questions/4731637/killing-processes-opened-with-popen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!