用c实现进程监控,如果某一进程退出则重启

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/types.h>  
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>



//要监控的程序
#define P1 "hello1"
#define P2 "hello2"
#define P3 "hello3"
#define PATH "."

/*****************************/
int is_run(char *name);
void killall_hello(void);
/*****************************/


//运行返回1,没有运行返回0
int is_run(char *name)
{
    int ret = -1;
    char buf[256] = {'\0'};
    snprintf(buf, sizeof(buf), "pidof %s >> /dev/null", name); 
    ret = system(buf);

    if(!WEXITSTATUS(ret)){ //#include <sys/wait.h>
        printf("%s is running!\n", name);
        return 1;
    }
    else{
        printf("%s is not running!\n", name);
        return 0;
    }
}

void killall_hello(void)
{ 
    char buf[128] = {'\0'};
    snprintf(buf, sizeof(buf), "killall %s", P1);
    system(buf);
    snprintf(buf, sizeof(buf), "killall %s", P2);
    system(buf);
    snprintf(buf, sizeof(buf), "killall %s", P3);
    system(buf);

}


int main(int argc, char **argv)
{
    int p1_ret = -1;
    int p2_ret = -1;
    int p3_ret = -1;
    char buf[128];
    bzero(buf, sizeof(buf));


    while(1){

    p1_ret = is_run(P1);
    p2_ret = is_run(P2);
    p3_ret = is_run(P3);

    if (!(p1_ret && p2_ret && p3_ret))
    {
        killall_hello(); 
        printf("rerun hello3\n");
        snprintf(buf, sizeof(buf), "%s/%s &", PATH, P3);
        system(buf);

    //打印日志信息
    system("date >> w.log");
    if(!p1_ret){
        snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P1, P3);
        system(buf);
    }else if(!p2_ret){
        snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P2, P3);
        system(buf);
    }else if(!p3_ret){
        snprintf(buf, sizeof(buf), "echo %s not run , killall , run %s >> w.log", P3, P3);
        system(buf);
            }
        }
    sleep(5);
    }
    exit(0);
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值