參考資訊:
https://github.com/pasce/daemon-skeleton-linux-c
main.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> static void run_daemon(void) { int x = 0; pid_t pid = 0; pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } if (pid > 0) { exit(EXIT_SUCCESS); } if (setsid() < 0) { exit(EXIT_FAILURE); } signal(SIGCHLD, SIG_IGN); signal(SIGHUP, SIG_IGN); pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } if (pid > 0) { exit(EXIT_SUCCESS); } umask(0); chdir("/"); for (x = sysconf(_SC_OPEN_MAX); x >= 0; x--) { close (x); } system("echo 123 > /tmp/daemon_start"); sleep(3); system("echo 123 > /tmp/daemon_stop"); } int main(int argc, char **argv) { run_daemon(); return 0; }
執行
$ gcc main.c -o main $ ./main $ ls /tmp/daemon* /tmp/daemon_start /tmp/daemon_stop