Created
October 13, 2014 15:24
-
-
Save bcho/1403a23e8bf7e91d8d3d to your computer and use it in GitHub Desktop.
trick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * We said a process is a daemon when: | |
| * | |
| * - its parent process terminates, | |
| * - the daemon process attach to init (1) process. | |
| * | |
| * Usually we will close its STDIN / STDOUT / STDERR and chroot to ``/``. | |
| */ | |
| #include <fcntl.h> | |
| #include <unistd.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| void daemonize(); | |
| void run_in_background(); | |
| int | |
| main() | |
| { | |
| pid_t child_pid; | |
| switch ((child_pid = fork())) { | |
| case -1: | |
| perror("cannot fork"); | |
| break; | |
| case 0: /* in child process */ | |
| daemonize(); | |
| run_in_background(); | |
| break; | |
| default: /* in parent process */ | |
| printf("child process running in: %d\n", child_pid); | |
| // Detach the child process to ``init``. | |
| exit(0); | |
| } | |
| return 0; | |
| } | |
| void daemonize() | |
| { | |
| int devnull_fd; | |
| // Change path to ``/``. | |
| if (chdir("/") != 0) | |
| perror("cannot change path to root"); | |
| if ((devnull_fd = open("/dev/null", O_RDWR, 0)) == -1) | |
| perror("cannot open /dev/null"); | |
| // Close STDIN / STDOUT / STDERR. | |
| dup2(devnull_fd, STDIN_FILENO); | |
| dup2(devnull_fd, STDOUT_FILENO); | |
| dup2(devnull_fd, STDERR_FILENO); | |
| // Clean up. | |
| if (devnull_fd > 2) | |
| close(devnull_fd); | |
| } | |
| // Task that will be running in the background. | |
| void run_in_background() | |
| { | |
| while (1) { | |
| // Sleep for 2 secs... | |
| sleep(2); | |
| } | |
| } | |
| /* | |
| * Run result: | |
| * | |
| * $ ./d | |
| * child process running in: 28000 | |
| * $ ps -p 28000 -o ppid= | |
| * 1 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment