Skip to content

Instantly share code, notes, and snippets.

@AvianFlu
Created February 25, 2012 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AvianFlu/1910390 to your computer and use it in GitHub Desktop.
Save AvianFlu/1910390 to your computer and use it in GitHub Desktop.
A barebones daemonizer.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[]) {
char *filename = argv[0];
char **args = &argv[1];
int pid;
signal(SIGHUP, SIG_IGN);
pid = fork();
if (pid < 0) {
/* this is an error */
perror("fork()");
exit(1);
}
else if (pid > 0) {
/* this is the parent */
printf("Child pid is %d", pid);
exit(0);
}
/* this is the child */
if (setsid() < 0) {
perror("setsid()");
exit(1);
}
umask(022);
if (execvp(filename, args) < 0) {
perror("execvp()");
exit(1);
}
/* there's really no way to get here, ever. */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment