Skip to content

Instantly share code, notes, and snippets.

@mmalecki
Created December 15, 2011 23:22
Show Gist options
  • Save mmalecki/1483446 to your computer and use it in GitHub Desktop.
Save mmalecki/1483446 to your computer and use it in GitHub Desktop.
Some example of daemonizing a process
#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