1.守护进程(Daemon)是运行在后台的一种特殊的进程,它独立于控制终端并且周期性的执行某种任务或者等待处理某些发生的时间。
2.守护进程及其特征
守护进程最重要的特征是在后台进行的,这是与DOS下的常驻内存TSR相似。他可以在linux系统启动时从启动脚本/etc/rc.d中启动,也可以由作业规划进程crond启动,还可以由用户终端执行.
下面是一个简单的守护进程的例子,每隔六秒钟向/tmp目录下的test.log中写入时间,直到进程结束。
//init programe init.c
#include
#include
#include
#include
#include
#include
void init_daemon(void)
{
int pid;
int i;
if (pid = fork())
exit(0);//if it's parental process,exit
else if (pid < 0)
exit(1);//fork() failed,exit
//if it is the first child process,the deamon process should run
setsid();//The first child process to be the new group and process
//leader,and escape from the control terminal
if (pid = fork())
exit(0);//end the first process
else if (pid < 0)
exit(1);//fork() failed,exit
//if it is the 2nd process,continue
//the 2nd process is not a leader of the group and process
for (i = 0; i < NOFILE; ++i)//close the file's mark
close(i);
chdir("/tmp");//change directory to /tmp
umask(0);//重设文件创建掩模]
return;
}
//main programe test.c
#include
#include
void init_daemon(void);
int main()
{
FILE *fp;
time_t t;
init_daemon();//初始化daemon
while (1) {
sleep(6);
if ((fp = fopen("test.log","a")) >= 0) {
t = time(0);
fprintf(fp,"I'm here at %s",asctime(localtime(&t)));
fclose(fp);
}
}
return 0;
}
运行如下
caojiangfeng@caojiangfeng-laptop:~/Code/C$ gcc -g -o test init.c test.c
caojiangfeng@caojiangfeng-laptop:~/Code/C$./test
在/tmp目录下看test.log如下
caojiangfeng@caojiangfeng-laptop:~/Code/C$ cat /tmp/test.log
I'm here at Fri Mar 5 19:49:17 2010
I'm here at Fri Mar 5 19:49:23 2010
I'm here at Fri Mar 5 19:49:29 2010
I'm here at Fri Mar 5 19:49:35 2010
I'm here at Fri Mar 5 19:49:41 2010
I'm here at Fri Mar 5 19:49:47 2010
I'm here at Fri Mar 5 19:49:53 2010
...
阅读(1176) | 评论(0) | 转发(0) |