//----------------------------------------------------
//AUTHOR: lanyang123456
//DATE: 2014-11-10
//---------------------------------------------------
#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
//守护进程初始化函数
void init_daemon(void)
{
int pid;
int i;
if(pid = fork())
exit(0); //是父进程,结束父进程
else if(pid < 0)
exit(1); //fork失败,退出
//是第一子进程,后台继续执行
setsid(); //第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if(pid = fork())
exit(0); //是第一子进程,结束第一子进程
else if(pid < 0)
exit(1); //fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长
for(i = 0; i < NOFILE; ++i) //关闭打开的文件描述符
close(i);
chdir("/tmp"); //改变工作目录到/tmp
umask(0); //重设文件创建掩模
return;
}
int main()
{
FILE *fp;
time_t t;
signal(SIGCHLD, SIG_IGN); /* 忽略子进程结束信号,防止出现僵尸进程 */
init_daemon();//初始化为Daemon
while (1)//每隔一分钟向test.log报告运行状态
{
sleep(60);//睡眠一分钟
if ((fp=fopen("test.log","a")) >=0) {
t=time(0);
fprintf(fp, "time now = %s", asctime(localtime(&t)));
fclose(fp);
}
}
}
$gcc -o test test.c
$./test
$ ps -axj
PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND
1676 4656 4655 4655 ? -1 S 1000 0:00 ./test
$ cat /tmp/test.log
time now = Mon Nov 10 15:12:27 2014
time now = Mon Nov 10 15:13:27 2014
time now = Mon Nov 10 15:14:27 2014
time now = Mon Nov 10 15:15:27 2014
参考
http://blog.csdn.net/zg_hover/article/details/2553321
http://www.cnblogs.com/wblyuyang/archive/2011/11/14/2248849.html