Justin
Justin

Reputation: 11

Why should I use fork() to daemonize my process?

According to my purpose, I just want to let my process be running in the background. Then I could write normal program and run it with the following command: nohup myprogram 1>2 2>/dev/null &

Then this program will be running in the background, just like as a daemon.

With this way, I do not need to call fork() for running in background. So my question is what is the difference to run program in background with the above command between using fork() function?

Upvotes: 1

Views: 911

Answers (1)

axiac
axiac

Reputation: 72226

TL;DR the fork() call is not needed, it just helps providing a nice UI for the users of the program.

A daemon uses fork() to create a duplicate of it. The child process then keeps running (in the background). The parent process may produce some output (status) then it exits.

Of course you can write only the child part of the program and launch it using the command line you posted:

$ nohup myprogram 1>2 2>/dev/null &

But if you write the daemon and I have to use it, I certainly prefer to use a simpler command line, without all that scaffolding needed to put the program in background and ensure its output doesn't make it stop and so on:

$ myprogram        # there is no need for anything else

Upvotes: 3

Related Questions