代码:
#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
void init_daemon(void)
{
int pid;
int i;
//first process
if (pid=fork())
{
exit(0);
}
else if(pid < 0)
{
printf("forck() error!\n");
exit(1);
}
setsid();
//second process
if (pid=fork())
{
exit(0);
}
else if(pid < 0)
{
printf("forck() error!\n");
exit(1);
}
//close file
for(i=0; i<NOFILE; ++i)
{
close(i);
}
//change directy
chdir("/home/hailonxi");
umask(0);
return;
}
int main()
{
FILE *fp;
time_t t;
init_daemon();
//This is the operation in the daemon process
while(1)
{
sleep(20);
if ((fp=fopen("test.log","a")) >= 0){
t=time(0);
fprintf(fp,"i am here at %s\n",asctime(localtime(&t)));
fclose(fp);
}
}
}
编译&运行:
//查看守护进程
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ gcc daemon.c
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ./a.out
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ps -ef | grep a.out
hailonxi 29978 1 0 15:52 ? 00:00:00 ./a.out
hailonxi 29982 11183 0 15:52 pts/9 00:00:00 grep a.out
//守护进程后台运行 ps看不到
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ps
PID TTY TIME CMD
11183 pts/9 00:00:00 bash
29983 pts/9 00:00:00 ps