Run php script as daemon process

后端 未结 14 1587
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:36

I need to run a php script as daemon process (wait for instructions and do stuff). cron job will not do it for me because actions need to be taken as soon as instruction arr

14条回答
  •  [愿得一人]
    2020-11-22 12:11

    If you can - grab a copy of Advanced Programming in the UNIX Environment. The entire chapter 13 is devoted to daemon programming. Examples are in C, but all the function you need have wrappers in PHP (basically the pcntl and posix extensions).

    In a few words - writing a daemon (this is posible only on *nix based OS-es - Windows uses services) is like this:

    1. Call umask(0) to prevent permission issues.
    2. fork() and have the parent exit.
    3. Call setsid().
    4. Setup signal processing of SIGHUP (usually this is ignored or used to signal the daemon to reload its configuration) and SIGTERM (to tell the process to exit gracefully).
    5. fork() again and have the parent exit.
    6. Change the current working dir with chdir().
    7. fclose() stdin, stdout and stderr and don't write to them. The corrrect way is to redirect those to either /dev/null or a file, but I couldn't find a way to do it in PHP. It is possible when you launch the daemon to redirect them using the shell (you'll have to find out yourself how to do that, I don't know :).
    8. Do your work!

    Also, since you are using PHP, be careful for cyclic references, since the PHP garbage collector, prior to PHP 5.3, has no way of collecting those references and the process will memory leak, until it eventually crashes.

提交回复
热议问题