PHP Program Daemon Process

Source: Internet
Author: User
The general server program is running in the system background, which is very different from the normal interactive command-line program. There is a function daemon in glibc. Call this function, you can make the current process out of the terminal into a daemon, the concrete content see man daemon. There is no such function in PHP, of course, if you are interested, you can write a PHP extension function to implement.

There are 2 ways to implement daemons in the PHP command-line program:
First, the use of nohup

Nohup php myprog.php > Log.txt &

The daemon is implemented here.

PHP myprog.php is executed separately, and when CTRL + C is pressed, the program execution is aborted, and the current process and child processes are kill.

PHP myprog.php &, so that the execution of the program, although also to run in the background, is actually dependent on the terminal, when the user exits the terminal process will be killed.
Second, the use of PHP code to achieve

function Daemonize () {$pid = Pcntl_fork (), if ($pid = =-1) {Die ("fork (1) failed!\n");} ElseIf ($pid > 0) {//Let the user-initiated process quit exit (0);} Create a new session that differs from Terminal posix_setsid (), $pid = Pcntl_fork (), if ($pid = =-1) {Die ("fork (2) failed!\n");} ElseIf ($pid > 0) {//parent process exits, remaining child process becomes the final standalone process exit (0);}} Daemonize (); sleep (1000);

With the above code can be implemented daemon, when your PHP program needs to be run in the background, only need to call a packaged function daemonize ().
Note: There is no redirection for standard input and output here.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.