日期:2014-05-16 浏览次数:20935 次
if ( (pid=fork())<0 ){
printf("error fork()\n");
exit(1) ;
}
else if (pid!=0) {
exit(0);
}
// ...............................................................some other ,but have no fork()
if ( (pid=fork()<0) ){
fputs("error fork()\n",stdout);
exit(1) ;
}
else if (pid!=0) {
exit(0);
}
void daemonize(const char *cmd)
{
int i,fd0,fd1,fd2;
pid_t pid;
struct rlimit rl;
struct sigaction sa;
umask(0);
if ( getrlimit(RLIMIT_NOFILE,&rl)<0 ){
printf("%s can't get file limit.\n",cmd);
exit(1) ;
}
if ( (pid=fork())<0 ){
printf("error fork()\n");
exit(1) ;
}
else if (pid!=0) {
exit(0);
}
setsid();//creates a session and sets the process group ID.
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags=0;
if (sigaction(SIGHUP,&sa,NULL)<0){
printf("error sigaction()");
exit(1) ;
}
if ( (pid=fork()<0) ){
fputs("error fork()\n",stdout);
exit(1) ;
}
else if (pid!=0) {
exit(0);
}
/*
if ( chdir("/tmp")<0 ){
FILE *fp=fopen("err","w");
fprintf(fp,"%d",errno);
fprintf(fp,"woj");
printf("error chdir()\n");
exit(1) ;
}
*/
if (rl.rlim_max == RLIM_INFINITY){
rl.rlim_max = 1024;
}
for(i=0;i<rl.rlim_max;i++){
close(i);
}
fd0=open("/dev/null",O_RDWR);
fd1=dup(0);
fd2=dup(0);
openlog(cmd,LOG_CONS,LOG_DAEMON);
/*
if(fd0!=0||fd1!=0||fd2!=0){
syslog(LOG_ERR,"unexpected file descriptors %d %d %d\n",fd0,fd1,fd2);
exit(1);
}
*/
}