PHP Extender Implementation Daemon

Source: Internet
Author: User
Tags php code

General server programs are running in the background of the system, which is very different from ordinary interactive command-line programs. There is a function daemon in the glibc. Calling this function allows the current process to be detached from the terminal into a daemon, as described in Man daemon. PHP does not have this function temporarily, of course, if you are interested, you can write a PHP extension function to achieve.

There are 2 ways to implement daemons for PHP command-line programs:

First, the use of nohup

copy code code as follows:


nohup php myprog.php > Log.txt &

The daemon is implemented here.

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

PHP myprog.php, so that the execution of the program, although also into the background running, is actually dependent on the terminal, when the user quit the terminal process will be killed.

Second, the use of PHP code to achieve

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 function Daemonize () {$pid = Pcntl_fork (); if ($pid = = 1) {die ("fork (1) failed!n");} elseif ($pid > 0) {//Let user initiated Process exit exit (0);   Establish a new session that is different from the terminal to get rid of the terminal posix_setsid (); $pid = Pcntl_fork ();   if ($pid = = 1) {die ("fork (2) Failed!n");} elseif ($pid > 0) {//parent process exits, leaving child process as final standalone process exit (0);} Daemonize (); Sleep (1000);

With the above code can be implemented daemon, when your PHP program needs to switch to the background to run, only need to call a good package function daemonize () can be.
Note: There is no redirection to achieve standard input/output.

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.