Last active
December 2, 2016 10:51
-
-
Save josephok/5a1e547a96ce4abb2cd323057e9c04fa to your computer and use it in GitHub Desktop.
daemon process
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 <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <stdio.h> | |
#include <fcntl.h> | |
int my_daemon() { | |
int maxfd, fd; | |
// first fork, become background process | |
switch (fork()) { | |
case -1: return -1; | |
case 0: break; | |
default: _exit(EXIT_SUCCESS); | |
} | |
// become session leader | |
if (setsid() == -1) | |
{ | |
return -1; | |
} | |
// second fork, ensure we won't become session leader | |
switch (fork()) { | |
case -1: return -1; | |
case 0: break; | |
default: _exit(EXIT_SUCCESS); | |
} | |
// set umask | |
umask(0); | |
// chdir | |
chdir("/"); | |
// close all opened fds | |
maxfd = sysconf(_SC_OPEN_MAX); | |
for (fd = 0; fd < maxfd; ++fd) | |
{ | |
close(fd); | |
} | |
// reopen stdin to /dev/null | |
close(STDIN_FILENO); | |
fd = open("/dev/null", O_RDWR); | |
dup2(STDIN_FILENO, STDOUT_FILENO); | |
dup2(STDIN_FILENO, STDERR_FILENO); | |
return 0; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
printf("I am a daemon process\n"); | |
my_daemon(); | |
while (1) { | |
sleep(5); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment