James Kuszmaul | 82f6c04 | 2021-01-17 11:30:16 -0800 | [diff] [blame^] | 1 | /** |
| 2 | * @file daemon.c Daemonize process |
| 3 | * |
| 4 | * Copyright (C) 2010 Creytiv.com |
| 5 | */ |
| 6 | #include <sys/types.h> |
| 7 | #include <sys/stat.h> |
| 8 | #ifdef HAVE_UNISTD_H |
| 9 | #include <unistd.h> |
| 10 | #endif |
| 11 | #include <stdlib.h> |
| 12 | #include <signal.h> |
| 13 | #include <stdio.h> |
| 14 | #include <re_types.h> |
| 15 | #include <re_mbuf.h> |
| 16 | #include <re_sys.h> |
| 17 | |
| 18 | |
| 19 | /** |
| 20 | * Daemonize process |
| 21 | * |
| 22 | * @return 0 if success, otherwise errorcode |
| 23 | */ |
| 24 | int sys_daemon(void) |
| 25 | { |
| 26 | #ifdef HAVE_FORK |
| 27 | pid_t pid; |
| 28 | |
| 29 | pid = fork(); |
| 30 | if (-1 == pid) |
| 31 | return errno; |
| 32 | else if (pid > 0) |
| 33 | exit(0); |
| 34 | |
| 35 | if (-1 == setsid()) |
| 36 | return errno; |
| 37 | |
| 38 | (void)signal(SIGHUP, SIG_IGN); |
| 39 | |
| 40 | pid = fork(); |
| 41 | if (-1 == pid) |
| 42 | return errno; |
| 43 | else if (pid > 0) |
| 44 | exit(0); |
| 45 | |
| 46 | if (-1 == chdir("/")) |
| 47 | return errno; |
| 48 | (void)umask(0); |
| 49 | |
| 50 | /* Redirect standard files to /dev/null */ |
| 51 | if (freopen("/dev/null", "r", stdin) == NULL) |
| 52 | return errno; |
| 53 | if (freopen("/dev/null", "w", stdout) == NULL) |
| 54 | return errno; |
| 55 | if (freopen("/dev/null", "w", stderr) == NULL) |
| 56 | return errno; |
| 57 | |
| 58 | return 0; |
| 59 | #else |
| 60 | return ENOSYS; |
| 61 | #endif |
| 62 | } |