#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
int result;
int isDaemon = 0;
while( (result = getopt(argc, argv, "d")) != -1){
switch(result){
case 'd':
isDaemon = 1;
break;
case ':':
case '?':
exit(EXIT_FAILURE);
}
}
if (isDaemon){
daemon(0, 0);
}
while(1){
sleep(1);
}
exit(EXIT_SUCCESS);
return 0;
}
void closeall(int fd){
int fdlimit = sysconf(_SC_OPEN_MAX);
while (fd < fdlimit){
close(fd++);
}
}
int daemon (int nochdir, int noclose){
switch (fork()){
case 0:
break;
case -1:
return -1;
default:
exit(0);
}
if (setsid()<0){
return -1;
}
switch (fork()){
case 0:
break;
case -1:
return -1;
default:
exit(0);
}
if (!nochdir){
chdir("/");
}
if (!noclose){
closeall(0);
open("/dev/null", O_RDWR);
dup(0); dup(0);
}
return 0;
}