I have a C program which I want to run as a daemon. I'm working in ubuntu 14.04LTS. Which is the right way to do that? Can anyone help?
And now, the Ubuntu answer.
The right way to do that is under the dæmon manager that comes with Ubuntu 14. What others have said here about designing a program explicitly to be a dæmon, and calling a
daemon() library function, is entirely wrongheaded. Ironically, Ubuntu had upstart for three LTS releases prior to version 14 LTS — since Ubuntu 6.10 in 2006 in fact. It's had a dæmon manager, of one sort or another, ever since.
The right answer for people with proper service management has been that you do not call
daemon() and you do not take special steps to "be a dæmon". And for some people this has been the right answer since the early 1990s. Even 2006 was somewhat late to the party. ☺ Even so, it has definitely been the right answer for the past ten years when it comes to Ubuntu.
What you do is simple. You set up an upstart "job" file that tells upstart when and how to invoke your program. upstart invokes it already dæmonized, without a controlling terminal and with a predictable and unvarying initial process state. Your program does nothing special and simply runs, writing logs and error messages to standard error in the normal way. You arrange in the job file how upstart deals with what is written to standard error.
The upstart Cookbook describes all of this in detail, including the various stanzas controlling startup events and log handling. And there's plenty on the subject here and on AskUbuntu.
Be prepared for the fact that the world will change on you quite significantly if you later upgrade to Ubuntu 16 LTS. But even then do nothing special in the code and simply run under a dæmon manager will remain the right answer.
- James Hunt and Clint Byrum (2014). "Console". Upstart Cookbook.
- init Ubuntu 14.04 manual pages. Canonical.
- Jonathan de Boyne Pollard (2001). Mistakes to avoid when designing Unix dæmon programs. Frequently Given Answers.
If your matter is to run the program out of a terminal here are some ways (your program must not ask for any user input):
nohup program > program.log 2>program.err &. Then you can exit the terminal.
echo "program > program.log 2>program.err" | at now
echo "program > program.log 2>program.err" | batch.
as a service by a boot script.
If you program is asking for user input then it will be not possible to run it outside a terminal the best is to use a
tux session then to detach the from the terminal.