Created
June 11, 2010 09:19
-
-
Save infynyxx/434275 to your computer and use it in GitHub Desktop.
code to create daemon in Linux
This file contains hidden or 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 <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