可以分三步来做: 做两个简单的守护进程,并能正常运行 监控进程是否在运行 启动进程 综合起来就可以了,代码如下: 被监控进程thisisatest.c(来自): #include #include #include #include #include #include #include #include void init_daemon() { int pid; int i; pid=fork(); if(pid<0) exit(1); //创建错误,退出 else if(pid>0) //父进程退出 exit(0); setsid(); //使子进程成为组长 pid=fork(); if(pid>0) exit(0); //再次退出,使进程不是组长,这样进程就不会打开控制终端 else if(pid<0) exit(1); //关闭进程打开的文件句柄 for(i=0;i=0) { time(&t); fprintf(fp,"current time is:%s\n",asctime(localtime(&t))); //转换为本地时间输出 fclose(fp); } } return; } 监控进程monitor.c: #include #include #include #include #include #include #include #include #include #include #include #define BUFSZ 150 void init_daemon() { int pid; int i; pid=fork(); if(pid<0) exit(1); //创建错误,退出 else if(pid>0) //父进程退出 exit(0); setsid(); //使子进程成为组长 pid=fork(); if(pid>0) exit(0); //再次退出,使进程不是组长,这样进程就不会打开控制终端 else if(pid<0) exit(1); //关闭进程打开的文件句柄 for(i=0;i=0) { count = does_service_work(); time(&t); if(count>0) fprintf(fp,"current time is:%s and the process exists, the count is %d\n",asctime(localtime(&t)), count); //转换为本地时间输出 else { fprintf(fp,"current time is:%s and the process does not exist, restart it!\n",asctime(localtime(&t))); //转换为本地时间输出 system("/home/user/daemon/thisisatest"); //启动服务 } fclose(fp); } } return; } 具体CMD命令: cc thisisatest.c -o thisisatest ./thisisatest cc monitor.c -o monitor ./monitor tail -f testfork3.log -- 查看日志
取消
评论