[英]stream_select(), signals and Stdin in PHP
I am trying to write a native PHP CLI application which reads data (log data) from stdin and does some handling after.我正在尝试编写一个本机 PHP CLI 应用程序,它从标准输入读取数据(日志数据)并在之后进行一些处理。
I got a first working version with a simple while-Loop:我得到了一个带有简单 while 循环的第一个工作版本:
while ($line = fgets(STDIN)) {
// Do my stuff here
}
When installing signal handling via通过安装信号处理时
function signal_handler(int $signo, mixed $siginfo) {
// ...
}
pcntl_async_signals(TRUE);
pcntl_signal(SIGHUP, 'signal_handler');
this works partly: The signals are only processed after each fgets()
.这部分起作用:信号仅在每个
fgets()
之后处理。
I tried to use stream_select()
with NULL as timeout and some other stuff, but this lead to a massive system load:-)我尝试将
stream_select()
与 NULL 一起用作超时和其他一些东西,但这会导致大量系统负载:-)
Is there any best practice to use stream_select()
and fgets()
on stdin to read data until it's "ready" and wait/pause indefinitely else but let signals being processed?是否有任何最佳实践在 stdin 上使用
stream_select()
和fgets()
来读取数据直到它“准备好”并无限期地等待/暂停,但让信号被处理?
You can use stream_set_blocking(STDIN, 0);
您可以使用
stream_set_blocking(STDIN, 0);
to remove the blocking.移除阻塞。
Example:例子:
function signal_handler(int $signo, $siginfo) {
exit("signal caught\n");
}
stream_set_blocking(STDIN, 0);
pcntl_async_signals(TRUE);
pcntl_signal(SIGHUP, 'signal_handler');
echo "pid=" . posix_getpid() . "\n";
echo "Listening input...\n";
while (true) {
while ($line = fgets(STDIN)) {
echo "Input: '$line'\n";
}
}
Possible output:可能的 output:
Pid=46834
Listening input...
Input: 'test'
signal caught
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.