Skip to content

Instantly share code, notes, and snippets.

@infynyxx
Created June 11, 2010 09:19
Show Gist options
  • Save infynyxx/434275 to your computer and use it in GitHub Desktop.
Save infynyxx/434275 to your computer and use it in GitHub Desktop.
code to create daemon in Linux
#include <unistd.h>
#include <sys/types.h>
#include <syslog.h>
#include <stdlib.h>
int daemonize();
void closelog();
int main(int argc, char **argv) {
daemonize();
openlog("test_daemon", LOG_PID, LOG_USER);
syslog(LOG_INFO, "%s", "Hello World!");
closelog();
return 1;
}
int daemonize() {
pid_t pid;
long n_desc;
int i;
//Initially fork
if ((pid = fork()) != 0) {
exit(0);
}
//set session id to make the process group and session group leader
setsid();
//second fork to make parent exit
if ((pid = fork()) != 0) {
exit(0);
}
//change current directory to root and clear the file mask mode
chdir("/");
umask(0);
//close all opened FDs
n_desc = sysconf(_SC_OPEN_MAX);
for (i = 0; i < n_desc; i++) {
close(i);
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment