Created
December 15, 2011 23:22
-
-
Save mmalecki/1483446 to your computer and use it in GitHub Desktop.
Some example of daemonizing a process
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 <unistd.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
int main() { | |
printf("Beginning to fork awesomesauce\n"); | |
// Fork the process. | |
int pid = fork(); | |
if (pid == 0) { | |
// `fork(2)` returns 0 to the parent process... | |
printf("Hello, I am the forked awesomesauce!\n"); | |
} | |
else if (pid < 0) { | |
// < 0 in case of failure | |
printf("Whoooops.\n"); | |
exit(pid); | |
} | |
else { | |
// And PID of the child process to the parent | |
printf("I am the parent awesomesauce (child was spawned as %d)!\n", pid); | |
// We want to daemonize, so quit here. | |
exit(0); | |
} | |
// Only child process can get here, parent process quits. | |
// Detach from the terminal | |
setsid(); | |
// Set the umask | |
umask(0); | |
// Redirect stdio to a file (only suitable if you want logging) | |
int out = open("out.log", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); | |
int err = open("err.log", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); | |
dup2(out, STDOUT_FILENO); | |
dup2(err, STDERR_FILENO); | |
for (;;) { | |
printf("Forked awesomesauce says: yo!\n"); | |
sleep(5); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment