DEV Community

Aldora
Aldora

Posted on

PHP Child Process and Signal-Part 2

  • When the signal of forked process doesn't get successful process from pcntl_wait(), it would stay untils it get processed successfully. (Once gets handled, it would not work for later pcntl_wait())

In the part 1, I talked about what happens when we kill parent process, then kill the child. In this part, I would talk about what would happen if we kill the process in reverse order.

pcntl_async_signals(true);

pcntl_signal(SIGTERM, function ($signal, $status) {
    echo "inside pcntl_signal\n";
    $pid = pcntl_wait($processStatus, WUNTRACED);
//    $pid = pcntl_wait($processStatus, WNOHANG);

    if (pcntl_wifexited($processStatus)) {
        $code = pcntl_wexitstatus($processStatus);
        print "pid $pid returned exit code: $code\n ";
    } else {
        print "$pid was unnaturally terminated\n ";
    }
//    print_r($processStatus);
//    echo "\n";
//    echo "signal: $signal\n";
//    print_r($status);
});
if ($pid = pcntl_fork()) {
    $parent = getmypid();
    echo "parent: $parent\n";

    sleep(60);
} else {
    $childPid = getmypid();
    echo "child pid: $childPid\n";

    sleep(60);
}
Enter fullscreen mode Exit fullscreen mode

Execute the above script, and according to the output of process pid, first use kill command to kill parent process, then kill child process. The total output would be like this:

parent: <parent pid>
child pid: <child pid>
inside pcntl_signal
pid -1 returned exit code: 0
inside pcntl_signal
pid <child pid> returned exit code: 0
Enter fullscreen mode Exit fullscreen mode

We still create two processes, one parent, one child. Kill the child, and this invokes the signal handler in the child process. However, pcntl_wait() only works when it's called in parent, so it returns -1. Then, we kill the parent, this time, the pcntl_wait() in parent handles the child process status info successfully. But this raises a noticeble point: the signal which can't be handled by pcntl_wait() in child process stays until successfully dealed by parent process.

Top comments (0)