Created
June 21, 2016 02:53
-
-
Save alvarow/32a68f80fac4137bdff6726a667612fc to your computer and use it in GitHub Desktop.
Sample daemonizing code in C
This file contains 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
#include <stdarg.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <signal.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
void bye(int sig); | |
int main( int argc, char *argv[] ) | |
{ | |
memset(argv[0], 0, strlen(argv[0])); // clears daemon name & arguments | |
strcpy(argv[0], "alvarowd"); // makes pretty/short on process table | |
// Forks to background | |
pid_t pid; | |
pid = fork(); | |
if (pid < 0) { | |
perror("fork"); | |
exit(1); // error encountered, no child has been created! | |
} | |
if (pid != 0) { // this is the parent, hence should exit | |
printf("Parent %d: I quit!\n", getpid()); | |
exit(0); | |
} | |
/* this is the child process of the child process of the actual calling process | |
and can safely be called a grandchild of the original process */ | |
setsid(); // make the process a group leader, session leader, and lose control tty | |
// umask(0); /* lose file creation mode mask inherited by parent */ | |
chdir("/"); /* change working dir, so we can umount */ | |
// close STDOUT, STDIN, STDERR | |
/* | |
close(STDIN_FILENO); | |
close(STDOUT_FILENO); | |
close(STDERR_FILENO); | |
*/ | |
// Fecha todos os descritores abertos pelo processo. | |
// int i; | |
// for (i=getdtablesize();i>=0;--i) close(i); | |
// i=open("/dev/null",O_RDWR); dup(i); dup(i); | |
signal(SIGTERM, bye); // Sends a message when going away | |
signal(SIGHUP, SIG_IGN); // ignore SIGHUP that will be sent to a child of the process | |
signal(SIGPIPE, SIG_IGN); // ignore SIGPIPE, for reading, writing to non-opened pipes | |
// every program using pipes should ignore this signal for being on the safe side | |
//daemon(); | |
printf("Child %d: Here I go!\n", getpid()); | |
printf("Child %d: looping forever... see you on eternity!\n", getpid()); | |
int i; for(i=0;i==0;i++) { | |
i--; | |
sleep(1); | |
}; | |
return 0; // never gets here | |
} // end of main | |
/* handler when program is terminated normally */ | |
void bye(int signal) | |
{ | |
printf("CHILD %d: I have received a SIGTERM\n", getpid()); | |
printf("CHILD %d: Now I die. Good bye.\n", getpid()); | |
exit(0); | |
//_exit(0); // Child should exit with _exit? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment