linux - [Solved-5 Solutions] Run php script as daemon process - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
How to run php script as daemon process ?
Linux - Solution 1:
You could start your php script from the command line (i.e. bash) by using
Linux - Solution 2:
- Another option is to use Upstart.
- It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.
- This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.
How to set it up:
Create a new script file at /etc/init/myphpworker.conf. Here is an example:
Starting & stopping your daemon:
Check if your daemon is running:
Linux - Solution 3:
Writing a daemon is like this:(this is posible only on *nix based OS-es - Windows uses services)
- Call umask(0) to prevent permission issues.
- fork() and have the parent exit.
- Call setsid().
- 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).
- fork() again and have the parent exit.
- Change the current working dir with chdir().
- 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 .
Linux - Solution 4:
We can use daemontools for this. It is smart, clean and reliable. In fact we use it for running all of our daemons.
Features.
- Automatically starts the daemon on reboot
- Automatically restart dameon on failure
- Logging is handled for you, including rollover and pruning
- Management interface: 'svc' and 'svstat'
- UNIX friendly (not a plus for everyone perhaps)
Linux - Solution 5:
- Use nohup
- Use screen and run your PHP program as a regular process inside that. This gives more control than using nohup.
- Use a daemoniser like http://supervisord.org/ (it's written in Python but can daemonise any command line program and give you a remote control to manage it).