PHP Daemon in 4 lines of code
Sometimes, you just need a script to start start doing "something" and run forever (or until the server gets restarted) with no much detail on what's going on.
A daemon is much more than simply leaving a script running alone in the background, however sometimes the needs are met with a very basic approach.
I've implemented this one on some scripts like one to keep my NAS "warm" and avoid getting disks idle by writing a file every each X seconds, or like another one to have my DNS updated because I don't have fixed IP at home.
Anyway, whatever you want to do, this is the way:
(I'll assume you met the requirements on your PHP installation to do this)
-
// DEMONIZE!
-
if( pcntl_fork() ){
-
}
Again, this is not a *real* daemon. It will just give you a script running alone.
After you have the script running in background, you can wrap your code into a "while(1){...}".
Then, you can write some "log" you want to keep watching.
Take a look:
This whould be the output in the log file:
-
(12:35:10) I'm still alive...
-
(12:36:10) I'm still alive...
-
(12:37:10) I'm still alive...
-
...
Ok, before a rain of people start blaming me, telling that a daemon is much (much) complex and you need to play with running-controls, semaphores and so forth, let me tell you again that this is the most basic way to have a script running alone without interfering at all.
Here, so far you have a script that will leave the console (assuming you're in Linux) after starting, and will be able to write a status info on your log.
At this time you could be wondering how to know if it's running or what. Well, I'm not a great Linux experimented user, but I know that you can issue "ps -ef | grep php" and you'll get a list of all "php" running processes.
If it appears in the list, there you have it.
If you want to finish it, then issue "kill XXXX" where XXXX is the process ID shown in the output of "ps".
Of course, you can then expand it to suit your needs and do whatever you want.
I hope this can give some advise to anyone and don't hesitate to ask.
Happy coding,
Pampa
