#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>
int i;
void daemonize(const char *cmd){
int i,fd0,fd1,fd2;
pid_t pid;
struct rlimit r1;
struct sigaction sa;
umask(0);
if(getrlimit(RLIMIT_NOFILE,&r1)<0)
perror("getrlimit()");
if((pid = fork())<0)
perror("fork()[1]");
else if(pid != 0)
exit(0);
setsid();
printf("%d\n",i++);
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if(sigaction(SIGHUP,&sa,NULL) < 0)
perror("sigaction()");
if((pid = fork())<0)
perror("fork()[2]");
else if(pid != 0)
exit(0);
printf("%d\n",i++);
printf("%ld\n",(long)getpid());
if(chdir("/") < 0)
perror("chdir()");
if(r1.rlim_max == RLIM_INFINITY)
r1.rlim_max = 1024;
for(i = 0;i < r1.rlim_max;i++)
close(i);
fd0 = open("/dev/null",O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
printf("%d\n",i++);
openlog(cmd,LOG_CONS,LOG_DAEMON);
if(fd0 != 0 || fd1 != 1 || fd2 != 2){
syslog(LOG_ERR,"unexpect file descriptors %d %d %d",fd0,fd1,fd2);
exit(1);
}
printf("%d\nENDING\n",i++);
}
int main(){
i = 1;
daemonize("hello");
pause();
printf("OMG!\n");
return 0;
}
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>
int i;
void daemonize(const char *cmd){
int i,fd0,fd1,fd2;
pid_t pid;
struct rlimit r1;
struct sigaction sa;
umask(0);
if(getrlimit(RLIMIT_NOFILE,&r1)<0)
perror("getrlimit()");
if((pid = fork())<0)
perror("fork()[1]");
else if(pid != 0)
exit(0);
setsid();
printf("%d\n",i++);
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if(sigaction(SIGHUP,&sa,NULL) < 0)
perror("sigaction()");
if((pid = fork())<0)
perror("fork()[2]");
else if(pid != 0)
exit(0);
printf("%d\n",i++);
printf("%ld\n",(long)getpid());
if(chdir("/") < 0)
perror("chdir()");
if(r1.rlim_max == RLIM_INFINITY)
r1.rlim_max = 1024;
for(i = 0;i < r1.rlim_max;i++)
close(i);
fd0 = open("/dev/null",O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
printf("%d\n",i++);
openlog(cmd,LOG_CONS,LOG_DAEMON);
if(fd0 != 0 || fd1 != 1 || fd2 != 2){
syslog(LOG_ERR,"unexpect file descriptors %d %d %d",fd0,fd1,fd2);
exit(1);
}
printf("%d\nENDING\n",i++);
}
int main(){
i = 1;
daemonize("hello");
pause();
printf("OMG!\n");
return 0;
}