Daemon linux
From Teknologisk videncenter
Example of creating a daemon in Linux:
- setsid() - damon will be the session leader. Sets Session ID (SID) and Group ID (GID) to Process ID (PID)
- Reopening stdin, stdout and stderr to /dev/null detaches the process from the controlling terminal and Parent PID is set to 1 (init or systemd - depending on Linux version/distribution)
- log_err() and log_to_log() are calls to a logging system not shown here
1 void daemon_create(void) {
2 pid_t pid;
3
4 pid = fork();
5 if(pid < 0){
6 log_err("Error in fork: %m"); // Write error to terminal
7 exit(1);
8 }
9 if(pid > 0){
10 exit(0); // Parent die
11 }
12 if(setsid() < 0){ // Make child session leader
13 log_err("Error in setsid: %m");
14 exit(1);
15 }
16 if ( freopen("/dev/null", "r", stdin) == NULL
17 || freopen("/dev/null", "w", stdout) == NULL
18 || freopen("/dev/null", "w", stderr) == NULL ) {
19 log_err("When creating daemon freopen from STDIN/OUT/ERR failed: %m");
20 }
21 log_to_syslog(); // Log to syslog only when in daemon mode
22 }
Checking the daemon
$ ps xo uname,pid,ppid,pgid,sid,tty,comm | grep -P '(my_daemon|COMMAND)'
USER PID PPID PGID SID TTY COMMAND
heth 778254 1 778254 778254 ? my_daemon