I have a script, which runs my PHP script each X times:
#!/bin/bash
while true; do
/usr/bin/php -f ./my-script.php
echo "Waiting..."
sleep 3
done
How can I start it as daemon?
I have a script, which runs my PHP script each X times:
#!/bin/bash
while true; do
/usr/bin/php -f ./my-script.php
echo "Waiting..."
sleep 3
done
How can I start it as daemon?
A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...
[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]
The simple way:
The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):
Add the following and save:
The better way to do this would be to create a Daemon via Upstart:
add the following:
Save this.
Confirm that it looks ok:
Now reboot the machine:
Now when you boot up your system, you can see the log file stating that your Daemon is running:
• Now you may start/stop/restart/get the status of your Daemon via:
restart: this will stop, then start a service
start: this will start a service, if it's not running
stop: this will stop a service, if it's running
status: this will display the status of a service
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
Another cool trick is to run functions or subshells in background, not always feasible though
Running a subshell in the background
To run it as a full daemon from a shell, you'll need to use
setsid
and redirect its output. You can redirect the output to a logfile, or to/dev/null
to discard it. Assuming your script is called myscript.sh, use the following command:This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first
/dev/null
with your /path/to/logfile.You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).