Difference between revisions of "Daemon linux"
From Teknologisk videncenter
m |
m |
||
Line 8: | Line 8: | ||
#include <stdlib.h> | #include <stdlib.h> | ||
#include <syslog.h> | #include <syslog.h> | ||
− | |||
− | |||
void daemon_create(void); | void daemon_create(void); | ||
int main(void) { | int main(void) { | ||
− | |||
printf("Starting my_daemon\n"); | printf("Starting my_daemon\n"); | ||
openlog("my_daemon", LOG_INFO, LOG_DAEMON); | openlog("my_daemon", LOG_INFO, LOG_DAEMON); | ||
daemon_create(); | daemon_create(); | ||
− | |||
for (int i=0; i < 100; i++) { | for (int i=0; i < 100; i++) { | ||
syslog(LOG_INFO,"Countet to %d", i); | syslog(LOG_INFO,"Countet to %d", i); | ||
Line 33: | Line 29: | ||
exit(1); | exit(1); | ||
} | } | ||
− | if(pid > 0){ | + | if(pid > 0) { |
syslog(LOG_INFO, "Parent dying"); | syslog(LOG_INFO, "Parent dying"); | ||
exit(0); // Parent die | exit(0); // Parent die | ||
Line 46: | Line 42: | ||
syslog(LOG_ERR, "When creating daemon freopen from STDIN/OUT/ERR failed: %m"); | syslog(LOG_ERR, "When creating daemon freopen from STDIN/OUT/ERR failed: %m"); | ||
exit(3); | exit(3); | ||
− | |||
} | } | ||
} | } |
Revision as of 07:28, 17 December 2022
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)
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <syslog.h>
5 void daemon_create(void);
6
7 int main(void) {
8 printf("Starting my_daemon\n");
9 openlog("my_daemon", LOG_INFO, LOG_DAEMON);
10 daemon_create();
11 for (int i=0; i < 100; i++) {
12 syslog(LOG_INFO,"Countet to %d", i);
13 sleep(2);
14 }
15 return(0);
16 }
17
18 void daemon_create(void) {
19 pid_t pid;
20
21 pid = fork();
22 if(pid < 0){
23 syslog(LOG_ERR, "Error in fork: %m");
24 exit(1);
25 }
26 if(pid > 0) {
27 syslog(LOG_INFO, "Parent dying");
28 exit(0); // Parent die
29 }
30 if(setsid() < 0){ // Make child session leader
31 syslog(LOG_ERR, "Error in setsid: %m");
32 exit(2);
33 }
34 if (freopen("/dev/null", "r", stdin) == NULL
35 || freopen("/dev/null", "w", stdout) == NULL
36 || freopen("/dev/null", "w", stderr) == NULL ) {
37 syslog(LOG_ERR, "When creating daemon freopen from STDIN/OUT/ERR failed: %m");
38 exit(3);
39 }
40 }
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