bbvan
bbvan

Reputation: 658

how to daemonize a script

I am trying to use daemon on Ubuntu, but I am not sure how to use it even after reading the man page.

I have the following testing script foo.sh

#!/bin/bash
while true; do
    echo 'hi' >> ~/hihihi
    sleep 10
done

Then I tried this command but nothing happened:

daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- foo.sh

The file hihihi was not updated, and I found this in the errlog:

20161221 12:12:36 foo: client (pid 176193) exited with 1 status

How could I use the daemon command properly?

Upvotes: 3

Views: 2597

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149165

AFAIK, most daemon or deamonize programs change the current dir to root as part of the daemonization process. That means that you must give the full path of the command:

daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- /path/to/foo.sh

If it still did not work, you could try to specify a shell:

daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- /bin/bash -c /path/to/foo.sh

Upvotes: 1

esvstn
esvstn

Reputation: 36

It is not necessary to use daemon command in bash. You can daemonize your script manually. For example:

#!/bin/bash

# At first you have to redirect stdout and stderr to /dev/null
exec >/dev/null
exec 2>/dev/null

# Fork and go to background
(
while true; do
    echo 'hi' >> ~/hihihi
    sleep 10
done
)&
# Parent process finished but child still working

Upvotes: 1

Related Questions