守护进程监测并启动程序

您所在的位置:网站首页 监控进程状态怎么写 守护进程监测并启动程序

守护进程监测并启动程序

2024-07-11 09:18| 来源: 网络整理| 查看: 265

通过进程的名称监控某个进程,如果该进程退出了,就马上启动该进程。通过system启动,如果该进程不退出或崩溃,将阻塞等待,将不会通过命令检查该进程是否存活。

源代码:deamon.c

#include #include #include #include #include #include #include #include #include #include #include #include int Init_daemon(void) { pid_t pid; int i; pid = fork(); //结束父进程,使得子进程成为后台,子进程会成为孤儿进程,最终被init进程 if (pid > 0) //父进程将得到子进程pid 一般得到的pid值大于0,子进程得到的pid值=0 { exit(0); } else if (pid < 0) { return -1; } /*建立一个新的进程组,,子进程成为这个进程组的首进程,以使该进程脱离所用终端*/ setsid(); /*再次新建一个子进程,退出父进程,保证该进程不是进程组长,同时让该进程无法再打开一个新的终端*/ pid = fork(); if (pid > 0) { exit(0); } else if (pid < 0) { return -1; } //关闭所用从父进程继承的不再需要的文件描述符 for (i = 0; i < NOFILE; close(i++)) ; //改变工作目录,使得进程不与任何文件系统联系 chdir("/"); //第五步:将文件屏蔽字设置为0 umask(0); //第六步:忽略SIGCHLD信号 signal(SIGCHLD, SIG_IGN); return 0; } void *MonitorProc(void *arg) { FILE *fp = NULL; FILE *pLogFile = NULL; // 文件指针 char buf[1024]; char spbuf[128]; int nums = -1; static int countNum = 0; while (1) { memset(buf, 0, sizeof(buf)); memset(spbuf, 0, sizeof(spbuf)); nums = -1; fp = NULL; fp = popen("ps -ef | grep autoTest.out | grep -v grep | wc -l", "r"); if (!fp) { continue; } else { while (fgets(buf, sizeof(buf) - 1, fp) != 0) { nums = atoi(buf); //if (nums


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3