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?
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.
To run ac 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.