Deokgyu Yang | 2c7e86b | 2020-04-28 10:56:11 +0900 | [diff] [blame] | 1 | /* |
| 2 | * daemonise.c: |
| 3 | * Fairly generic "Turn the current process into a daemon" code. |
| 4 | * |
| 5 | * Copyright (c) 2016-2017 Gordon Henderson. |
| 6 | ********************************************************************************* |
| 7 | */ |
| 8 | |
| 9 | #include <stdio.h> |
| 10 | #include <stdlib.h> |
| 11 | #include <unistd.h> |
| 12 | #include <syslog.h> |
| 13 | #include <signal.h> |
| 14 | #include <sys/stat.h> |
| 15 | |
| 16 | #include "daemonise.h" |
| 17 | |
| 18 | void daemonise (const char *pidFile) |
| 19 | { |
| 20 | pid_t pid ; |
| 21 | int i ; |
| 22 | FILE *fd ; |
| 23 | |
| 24 | syslog (LOG_DAEMON | LOG_INFO, "Becoming daemon") ; |
| 25 | |
| 26 | // Fork from the parent |
| 27 | |
| 28 | if ((pid = fork ()) < 0) |
| 29 | { |
| 30 | syslog (LOG_DAEMON | LOG_ALERT, "Fork no. 1 failed: %m") ; |
| 31 | exit (EXIT_FAILURE) ; |
| 32 | } |
| 33 | |
| 34 | if (pid > 0) // Parent - terminate |
| 35 | exit (EXIT_SUCCESS) ; |
| 36 | |
| 37 | // Now running on the child - become session leader |
| 38 | |
| 39 | if (setsid() < 0) |
| 40 | { |
| 41 | syslog (LOG_DAEMON | LOG_ALERT, "setsid failed: %m") ; |
| 42 | exit (EXIT_FAILURE) ; |
| 43 | } |
| 44 | |
| 45 | // Ignore a few signals |
| 46 | |
| 47 | signal (SIGCHLD, SIG_IGN) ; |
| 48 | signal (SIGHUP, SIG_IGN) ; |
| 49 | |
| 50 | // Fork again |
| 51 | |
| 52 | if ((pid = fork ()) < 0) |
| 53 | { |
| 54 | syslog (LOG_DAEMON | LOG_ALERT, "Fork no. 2 failed: %m") ; |
| 55 | exit (EXIT_FAILURE) ; |
| 56 | } |
| 57 | |
| 58 | if (pid > 0) // parent - terminate |
| 59 | exit (EXIT_SUCCESS) ; |
| 60 | |
| 61 | // Tidying up - reset umask, change to / and close all files |
| 62 | |
| 63 | umask (0) ; |
| 64 | chdir ("/") ; |
| 65 | |
| 66 | for (i = 0 ; i < sysconf (_SC_OPEN_MAX) ; ++i) |
| 67 | close (i) ; |
| 68 | |
| 69 | // Write PID into /var/run |
| 70 | |
| 71 | if (pidFile != NULL) |
| 72 | { |
| 73 | if ((fd = fopen (pidFile, "w")) == NULL) |
| 74 | { |
| 75 | syslog (LOG_DAEMON | LOG_ALERT, "Unable to write PID file: %m") ; |
| 76 | exit (EXIT_FAILURE) ; |
| 77 | } |
| 78 | |
| 79 | fprintf (fd, "%d\n", getpid ()) ; |
| 80 | fclose (fd) ; |
| 81 | } |
| 82 | } |