pcntl_wait没有被SIGTERM打断 [英] pcntl_wait not interrupted by SIGTERM

查看:167
本文介绍了pcntl_wait没有被SIGTERM打断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 pcntl_wait 的PHP文档,

According to the PHP docs for pcntl_wait,

wait函数会暂停当前进程的执行,直到退出子进程,或者传递了一个信号,其作用是终止当前进程或调用信号处理函数.

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

但是,当我运行以下代码并使用kill -s SIGTERM [pid]将SIGTERM发送到父进程时,信号处理程序仅在孩子退出后称为 (即,我必须等待睡眠完成) .pcntl_wait()不应该被SIGTERM打断吗?

However, when I run the following code and send SIGTERM to the parent process with kill -s SIGTERM [pid] the signal handler is only called after the child exits (i.e. I have to wait for the sleep to finish. Shouldn't pcntl_wait() be interrupted by SIGTERM?

fork_test.php:

fork_test.php:

<?php
  declare(ticks = 1);

  function sig_handler($signo) {
    switch ($signo) {
      case SIGTERM:
        echo 'SIGTERM' . PHP_EOL;
        break;
      default:
    }
  }

  pcntl_signal(SIGTERM, 'sig_handler');

  $pid = pcntl_fork();

  if ($pid == -1) {
     die('could not fork');
  }
  else if ($pid) {
    echo 'parent' . PHP_EOL;

    pcntl_wait($status);
  }
  else {
    echo 'child' . PHP_EOL;
    sleep(30);
  }
?>

输出(仅在等待30秒后才会显示SIGTERM):

Output (SIGTERM only appears after waiting 30 seconds):

$ php fork_test.php
child
parent
SIGTERM

PHP版本=> 5.3.3

推荐答案

您对pcntl_signal的调用指定应重新启动该调用.检查文档,默认情况下restart_syscallstrue .因此,在孩子终止之前,您对pcntl_signal的呼叫不会返回.

Your call to pcntl_signal specifies that the call should be restarted. Check the docs, restart_syscalls is true by default. So your call to pcntl_signal doesn't return until the child has terminated.

您没有呼叫刷新.因此,PHP可以将echo的输出保存在缓冲区中.

You have no call to flush. So PHP can hold the output of echo in a buffer.

因此,您所看到的行为恰恰是您所要求的行为.重新启动系统调用,并缓冲输出.

So the behavior you are seeing is precisely the behavior you are requesting. The system call is restarted and the output is buffered.

这篇关于pcntl_wait没有被SIGTERM打断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆