I want to make a script to be self-daemonizing, i.e., no need to invoke nohup $SCRIPT &>/dev/null &
manually on the shell prompt.
My plan is to create a section of code like the following:
#!/bin/bash
SCRIPTNAME="$0"
...
# Preps are done above
if [[ "$1" != "--daemonize" ]]; then
nohup "$SCRIPTNAME" --daemonize "${PARAMS[@]}" &>/dev/null &
exit $?
fi
# Rest of the code are the actual procedures of the daemon
Is this wise? Do you have better alternatives?
One of the requirements I have is that the script must be self contained; no other files are to accompany the script and there are to be no environment variables. This would require the script to be able to edit itself.
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.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
To start a daemon, if it is in the bin folder, then you could, for example, run sudo ./feeder -d 3 from the bin folder. hi, I have tested or used kill/killall to kill one deamon. But in a moment, the deamon will automatically restart(using bin/status, the status of the daemon is running).
In this post I'll show you how to create a self extracting bash script to automate the installation of files on your system. This script requires coreutils (for cat, tail), awk, gzip, tar and bash. There are 3 parts to the Base Self-Extracting Script
To be a true daemon you should chdir ("/") (or cd / inside your script), and fork so that the parent exits, and thus the original descriptor is closed. Perhaps run umask 0. You may not want to depend on the umask of the caller of the daemon.
I personally upvoted carlo's answer as it seems to be the most elegant and works both from terminal and inside scripts Show activity on this post. Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):
So the command would be: After that close your bash session,open another terminal and execute: ps -aux | egrep "script.sh" and you will see that your script is still running at the background. Of cource,if you want to stop it then execute the same command (ps) and kill -9 <PID-OF-YOUR-SCRIPT>
Here are things I see.
if [[ $1 != "--daemonize" ]]; then
Shouln't that be == --daemonize?
nohup $SCRIPTNAME --daemonize "${PARAMS[@]}" &>/dev/null &
Instead of calling your script again, you could just summon a subshell that's placed in a background:
(
Codes that run in daemon mode.
) </dev/null >/dev/null 2>&1 &
disown
Or
function daemon_mode {
Codes that run in daemon mode.
}
daemon_mode </dev/null >/dev/null 2>&1 &
disown
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With