Reputation: 3
I have successfully created a C program which runs an infinite loop waiting for a connecting through sockets. I would like to make it a daemon and be able to start and stop it. How can I do it? What changes should I do to my code to run in the background?
Upvotes: 0
Views: 2755
Reputation: 161
To run a c program as daemon you need to do the following steps.
// Create child process
process_id = fork();
//unmask the file mode
umask(0);
//change the directory as your home directory
strcpy(home,"HOME");
home=getenv(home);
chdir(home) ;
//set new session
sid = setsid();
close(STDIN_FILENO); open("/dev/null", O_RDWR);
close(STDOUT_FILENO); open("/dev/null", O_RDWR);
close(STDERR_FILENO); open("/dev/null", O_RDWR);
Upvotes: 1
Reputation: 239341
The classic tasks required to become a daemon are:
fork()
and have the parent exit, so that the process is not a process group leader;/dev/null
;setsid()
to make the process a session group leader of a new session with no controlling terminal.Without error-checking:
chdir("/);
if (fork() > 0)
_exit();
close(0);
close(1);
close(2);
open("/dev/null", O_RDWR);
dup(0);
dup(0);
setsid();
On Linux, glibc provides a daemon()
helper function to do these tasks.
Upvotes: 2