红联Linux门户
Linux帮助

Linux C语言检查进程是否存在

发布时间:2016-11-16 16:04:20来源:linux网站作者:Kevin_Smart
使用C语言根据进程名检查进程是否存在,然后重启进程。
 
/* 
*  COPYRIGHT NOTICE 
*  Copyright (C) 2016 HuaHuan Electronics Corporation, Inc. All rights reserved 
*  Author   :Kevin_fzs 
*  File Name:/home/kevin/works/projects/MIPS53003/drivers/webRestart.c 
*  Create Date  :2016/11/16 15:11 
*  Last Modified:2016/11/16 15:11 
*  Description  : 
*/  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>
int getRestartStatus()  
{  
char *name="/home/webserver/Rflag.txt";   
FILE *fd;  
int ret=0;
fd = fopen(name, "r");  
if(NULL == fd)  
return 1;  
else  
return 0;  
}
int main()  
{  
FILE *ptr = NULL;  
char cmd[128] = "ps -ef | grep appweb | grep -v grep | wc -l";  
int status = 0;  
char buf[150];  
int count;
while(1)  
{  
status = getRestartStatus(); //根据标志文件来决定是否要检查进程  
if(status)  
{  
if((ptr = popen(cmd, "r"))==NULL)  
{  
printf("popen err\n");
continue;  
}
memset(buf, 0, sizeof(buf));
if((fgets(buf, sizeof(buf),ptr))!= NULL) //获取进程和子进程的总数  
{  
count = atoi(buf);  
if(count <= 0) //当进程数小于等于0时,说明进程不存在  
{
system("/home/appweb_start.sh");  
printf("restart appweb \n");  
}
}
}  
usleep(200000);  
}  
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/26058.html