linux C监控程序

/************************************************************

  • FileName :Monitor.c
  • Author : Tobiu
  • Description: 守护进程;
  • Date : Apr 18, 2018

***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <error.h>

#define MAXFILE 3
#define USEPRINTF 1

/************************************************************

  • @Function : program_Running

  • @Description : 判断程序是否在运行

  • @Param :

  •   service	:	进程名
    
  • @return : exist : 1,no found value : 0
    ***********************************************************/
    int program_Running(char *service)
    {
    FILE *fp;
    char cmd[128], buf[1024];
    char *pLine;

    sprintf(cmd, “/bin/ps aux | /bin/grep %s | /bin/grep -v grep”, service);
    fp = popen(cmd, “r”);
    while( fgets(buf, sizeof(buf), fp) != NULL )
    {
    pLine = strtok(buf, “\n”);
    while( pLine )
    {
    if( strstr(pLine, service) )
    {
    pclose( fp );
    return 1;
    }
    pLine = strtok(NULL, “\n”);
    }
    }
    pclose( fp );
    return 0;
    }

int main(int argc, char* argv[])
{
if( USEPRINTF ) printf(“homecentor\n”);

pid_t pc, pid;

pc = fork();
if( pc < 0 )
{
	if( USEPRINTF ) printf("error fork\n");
	exit(1);
}
else if( pc > 0 )
{
	exit(0);
}
pid = setsid(); 
if( pid < 0 )
	perror("setsid error");

chdir("/"); 
umask(0);

int i;
for(i=0; i<MAXFILE; i++) 
	close(i);

while( 1 ) 
{
	/*监测homecentor*/
	if(!program_Running("homecenter"))
	{
		/* The program did not run */
		system("/usr/bin/killall -9 homecenter");    //杀进程
		system("/bin/taskset -c 0 /home/mycode/bin/homecenter &");    //重新启动
	}
	sleep(2);
} 			
return 0;

}

作者:Tobiu
来源:CSDN
原文:https://blog.csdn.net/localhostcom/article/details/79994230
版权声明:本文为博主原创文章,转载请附上博文链接!在这里插入代码片

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值