本文共 1006 字,大约阅读时间需要 3 分钟。
Table of Contents
#include#include #include #include #include #include void init_deamon(){ int pid; int i; /*如果是父进程,结束*/ if(pid=fork()) { exit(0); } else if(pid<0) { exit(1); } /* 是第一子进程,后台继续执行 * 第一自己成成为新的会话组长和进程组长*/ setsid(); /*与控制终端分离*/ if(pid=fork()) { exit(0);//结束第一子进程 } else if (pid<0) { exit(1); } /** * 是第二子进程,继续 * 第二子进程不再是会话组长 * 关闭打开的文件描述符 */ for(i=0;i
#include#include void init_deamon();int main(){ FILE *fp; time_t t; init_deamon(); while(1) { sleep(2);//每隔一分钟向test.log报告运行状态 if((fp=fopen("test.log", "a")) >= 0) { t = time(0); fprintf(fp, "I'm here at %s\n", asctime(localtime(&t))); fclose(fp); } }}
$ ./a.out $ more /tmp/test.log I'm here at Tue Feb 11 21:38:50 2020I'm here at Tue Feb 11 21:38:52 2020$ more /tmp/test.log I'm here at Tue Feb 11 21:38:50 2020I'm here at Tue Feb 11 21:38:52 2020I'm here at Tue Feb 11 21:38:54 2020
转载地址:http://jypaf.baihongyu.com/