Created
April 16, 2016 20:14
-
-
Save fffaraz/197dd36b30dcc5e3672d5632c25883e0 to your computer and use it in GitHub Desktop.
daemon basics
This file contains 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
// http://www.crankyotaku.com/2016/04/linux-programming-daemon-basics.html | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
int main(int argc, char *argv[]) | |
{ | |
int maxfd, fd; | |
switch(fork()){ | |
case -1: | |
exit(EXIT_FAILURE); | |
case 0: | |
break; | |
default: | |
_exit(EXIT_SUCCESS); | |
} | |
if(setsid() == -1){ | |
printf("Error becoming session leader\n"); | |
_exit(EXIT_FAILURE); | |
} | |
switch(fork()){ | |
case -1: | |
exit(EXIT_FAILURE); | |
case 0: | |
break; | |
default: | |
_exit(EXIT_SUCCESS); | |
} | |
umask(0); | |
chdir("/"); | |
maxfd = sysconf(_SC_OPEN_MAX); | |
for(fd = 0; fd < maxfd; fd++) | |
close(fd); | |
close(STDIN_FILENO); | |
fd = open("/dev/null", O_RDRW); | |
if(fd != STDIN_FILENO) | |
_exit(EXIT_FAILURE); | |
if(dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO) | |
_exit(EXIT_FAILURE); | |
if(dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO) | |
_exit(EXIT_FAILURE); | |
for(;;){ | |
//This daemon will run forever. use ps aux | grep ./[name of program] to | |
//find it and kill it. If you don't care to observe its | |
//properties while its running remove the endless for loop. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment