Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.