How to daemonize a bash script only if --daemon flag is given?

2

I have my script.sh and want to run it with ./script.sh or ./script.sh --daemon, having it remain in the foreground unless the --daemon flag is given, in which case it should detach and go into the background appropriately. I want the script to look like

[function definitions]

process_args

if [ "$BECOME_DAEMON" == "1" ]; then
    become_daemon
fi

while true; do
    read line <controller_fifo
    do_command $line
done

Is it possible to get the behavior I want? If so, what do I need to fill in for become_daemon? If not, what would be the best alternative?

nullUser

Posted 2015-04-01T02:04:35.083

Reputation: 593

Answers

2

I found the following to work:

[function definitions]

process_args

function command_loop {
    trap handle_term SIGTERM

    while true; do
        read line <controller_fifo && do_command $line &
        wait
    done
}

if [ "$BECOME_DAEMON" == "1" ]; then
    command_loop &> /dev/null &
    disown
else
    command_loop 
fi

Note that this method handles the SIGTERM signal gracefully in both cases (daemon or no daemon), whereas the original read loop I had posted would not handle a signal (signal handler would not be called until after another read line).

nullUser

Posted 2015-04-01T02:04:35.083

Reputation: 593