Note: Full source code for the example can be downloaded here.
One of the many things you don’t often do with PHP (actually, I’m not sure you do this much with any language) is daemonize a process. A daemon is program that runs in the background (read more here). On Unix systems, processes are usually created by forking the init process and then manipulating the process to your liking. To create a daemon though, you need to get the init process to adopt your process. To do that, as soon as you fork the parent process, you kill the parent. Since you child process is parent-less, the init process generally adopts it. Once that happens, your process has been daemonized.
What You Need To Know
In order to follow the example, you’ll probably want to read up on multi–processing in PHP and using POSIX in PHP. Aside from that, keep an open mind. There are probably better ways to do this (Nanoserv), but I think that doing it manually is a great way to learn more about systems programming and PHP.
Step 1: Fork It
The first thing that you need to do when daemonizing a process in PHP is fork the process. After that, we promptly kill the parent process so that the child process can be adopted.
//Set the ticks declare(ticks = 1); //Fork the current process $processID = pcntl_fork(); //Check to make sure the forked ok. if ( $processID == -1 ) { echo "\n Error: The process failed to fork. \n"; } else if ( $processID ) { //This is the parent process. exit; } else { //We're now in the child process. } |
Step 2: Detach It
Now that we have successfully forked the process and killed the parent, we need to detach the process from the terminal window. We do this so that when the terminal window closes, our process doesn’t close with it. Once that’s done, we get our processes’ id.
//Now, we detach from the terminal window, so that we stay alive when //it is closed. if ( posix_setsid() == -1 ) { echo "\n Error: Unable to detach from the terminal window. \n"; } //Get out process id now that we've detached from the window. $posixProcessID = posix_getpid(); |
Step 3: /var/run
Now that we have our processes’ id, we need to let the system know about it. To do this, we create a file in /var/run. This file can be named anything you want, just make sure that it’s unique and it ends with the .pid extension. In that file, we place the pid of our process and that’s it.
//Create a new file with the process id in it. $filePointer = fopen( "/var/run/phpprocess.pid" , "w" ); fwrite( $filePointer , $posixProcessID ); fclose( $filePointer ); |
Step 4: Do Something
Now that all the hard stuff is done, you can get to work. What do you want your process to do? For this example, I have mine adding 1 + 1 every 10 seconds. Nothing too difficult, but you can make your process do whatever you like. For instance, you could set up a server of some sort. Note that this the code is sitting in an infinite while loop. This is done so that the process doesn’t exit naturally.
//Now, do something forever. while (true) { $x = 1 + 1; sleep(10); } |
Step 5: Run It
To run this process as a daemon, all you need to do is save you file and run php <myfile>.php. You may need to execute it as a super user depending on how you permissions are set up. Once it’s run, you can check out the results of your hard work by running ps aux | less. Scroll to the bottom and your process should be there. In the screen shot below, mine is 3rd from the bottom.
Note: Full source code for the example can be downloaded here.
15 replies on “PHP Dark Arts: Daemonizing a Process”
[…] Czytaj więcej: PHP Dark Arts: Daemonizing a Process | Re-Cycled Air […]
[…] here to read the rest: PHP Dark Arts: Daemonizing a Process | Re-Cycled Air 分类: php 标签: php, quick-introduction 评论 (0) Trackbacks (0) 发表评论 […]
[…] This post was mentioned on Twitter by Manish Deo, Re-CycledAir. Re-CycledAir said: PHP Dark Arts: Daemonizing a Process http://fwds.me/5l […]
Does this work also on PHP Windows install?
Windows doesn’t have a directory called /var/run but forks seem to work fine on Windows too. Also, daemons in Windows are called “Services”, and there’s some special API you have to use to register, deregister, start and stop services. Shouldn’t be too complicated.
Who knew creating a service was this easy!
I’ve read that some people have had trouble creating services on OS X this way, but in general it seems to be pretty great. Thanks for visiting.
I am pooling a folder (FTP) using the crontab but i felt that a deamon would be a little nicer, thanks for the info i has given me a great starting point
Why are you using php for the forking? I see you’re using a terminal, so why don’t you do something like this:
$ php deamon.php &
This command launches the command in it’s own subshell. 🙂
I’ll be honest, I didn’t even think about doing it that way. Good catch.
Alex: You don’t have the PID for the process using & to fork and so don’t have access to a lot of the other PCNTL functions and Posix specific signalling stuff that PHP makes available but yeah, for most people wanting a process to run in the background using & is perfect!
Also you may wish to fire the daemon from a web script (i.e. to start a spooler job) and this is cleaner than having to call exec();
[…] Arts” series looking at some of the lesser used PHP features. This time he focuses in on daemonizing a process by forking it off into the background. One of the many things you don’t often do with PHP […]
[…] PHP Dark Arts: Daemonizing a Process […]
You should add some controlls to like your articles – facebook like or wordpress stars. I was looking for a way to create a daemon and this solves my problems.
Thank you!
http://dev.pedemont.com/sonic sonic php daemon might be worth checking out aswell