开发者

pcntl_signal isn't triggered by the child process

开发者 https://www.devze.com 2023-03-05 04:14 出处:网络
I want to achieve this: if the daemon gets SIGHUP than run the process again (as child) and kill the parent.

I want to achieve this:

if the daemon gets SIGHUP than run the process again (as child) and kill the parent.

When i'm running it, the first time is working:

> php test.php
> kill -HUP pid
> ps -ef |grep test.php
> result:... newPID test.php

The problem is that if now i'm killing the child process,the function is not triggered

> kill -HUP newPID
> ps -ef |grep test.php
> result: ... newPID(the same) test.php

The code:

test.php:
<?php
   declare(ticks = 1);

   $mypid = posix_getpid();

   function sig_ha开发者_高级运维ndler()
   {

   Global $mypid;
   echo "Received sighup, we need to reload ourselves now \n";
   echo "mypid:$mypid \n";
   system("(php test.php)>/dev/null &");

   posix_kill($mypid,9);

   }

   pcntl_signal(SIGHUP,  "sig_handler");

   sleep(500);

   ?>

This code works on PHP 5.2.9 but not on PHP 5.3.5. Is there any way to make it works also on that version?

Thanks!

Ronny


Signal handlers in PHP are not re-entrant. So any process you fork/spawn from within a signal handler cannot itself respond to signals. I'd love to see details if that exact code worked in PHP 5.2.9 because to my knowledge this behavior has been consistent.

So what can you do?

In many cases, the best option is to set a $signal_recd flag inside the signal handler that you poll periodically in your application.

I'm the author of a fairly popular PHP Daemon Library, https://github.com/shaneharter/PHP-Daemon

If i were you, I would just build your app on that and let it worry about auto-restarting, etc. But if nothing else, you can probably look at it's Core_Daemon::auto_restart() and signal handling code.


My suspicion here is that this is a bug in PHP. I'm still trying to confirm with absolute certainty, but as it stands we are having the same issue.

If you launch a child process and send a signal, the child process will receive and handle the signal. If you subsequently re-launch another child process from the parent script and follow up with another signal, the second signal is not received by the child process. I've tweaked, twiddled, and toiled to find a way around this issue in PHP 5.3.10 to no avail.

0

精彩评论

暂无评论...
验证码 换一张
取 消