【发布时间】:2013-09-16 12:38:55
【问题描述】:
以下脚本监视/dev/shm/test 的新文件并实时输出有关它的信息。
问题是当用户关闭浏览器时,inotifywait 进程保持打开状态,依此类推。
有什么办法可以避免吗?
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "a") // stderr is a file to write to
);
$process = proc_open('inotifywait -mc -e create /dev/shm/test/', $descriptorspec, $pipes);
if (is_resource($process)) {
header("Content-type: text/html;charset=utf-8;");
ob_end_flush(); //ends the automatic ob started by PHP
while ($s = fgets($pipes[1])) {
print $s;
flush();
}
fclose($pipes[1]);
fclose($pipes[0]);
fclose($pipes[2]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
?>
【问题讨论】:
-
你的代码包含一个无限循环。为什么你会期望它不会做那个无限循环?另外:您在这里使用的是哪个 SAPI?例如,如果您在 CLI 中启动该脚本并使用 CTRL+C 中止它,会发生什么情况? “子进程”被杀死了吗?
proc_open是打开子进程还是独立的?fgets的超时时间是多少?我的意思是,如果 STDOUT 没有可读取的内容,你会怎么做 - 等待多长时间? -
@hakre 我可以确认它在控制台模式下使用 CTRL+C 杀死了 inotifywait 进程。 fgets 没有超时,因为我尝试像 Jon 的回答一样检查
connection_aborted()和proc_terminate()但没有帮助,这很奇怪,因为据记录,PHP 只会在尝试输出某些内容后才知道连接被中止(我做)。另外,如果不检查这些函数,脚本应该在取消窗口加载时终止,你不觉得吗? -
你用的是什么php版本?