linux C监控程序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/localhostcom/article/details/79994230

需求:

    编写一个监控程序,用于检测某个服务是否在运行,如果没有运行,则重新启动。


/************************************************************
* 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;
}

猜你喜欢

转载自blog.csdn.net/localhostcom/article/details/79994230