if(pid=fork())
exit(0); //if it's parent process then over parent process
else if(pid< 0)
exit(1); //fork dismiss,exit
//it's the first child process ,then run in back
setsid(); //the first child process become the new session header and process header
//and leave control side
if(pid=fork())
exit(0); //if it's the first child process then over the process
else if(pid< 0)
exit(1); //fork faile,exit
//if it's the second process , go ahead
//the second process isn't the process header already
for(i=0;i< NOFILE;++i) //close and open file char
close(i);
chdir("/tmp"); //change work dir to /tmp
umask(0); //reset the file and recreate 掩模
return;
}
2. test.c清?
#include < stdio.h >
#include < time.h >
void init_daemon(void); //init function
main()
{
FILE *fp;
time_t t;
init_daemon(); //init become Daemon
while(1) //send a report to test.log every minute
{
sleep(60); //sleep one minute
if((fp=fopen("test.log","a")) >=0)
{
t=time(0);
fprintf(fp,"I'm here at %s\n",asctime(localtime(&t)) );
fclose(fp);
}
}
}