Jump to content
Sign in to follow this  
墨香年少

linux下用c++一秒检测一次程序是不是存在,不存在则拉起

Recommended Posts

#include <stdio.h>   
#include <stdlib.h>   
#include <unistd.h>   
#include <fcntl.h>   
#include <limits.h>   
#include <sys/types.h>   
#include <sys/wait.h>   
 
#define BUFSZ 150   
 
void err_quit(char *msg);

int main(int argc, char *argv[])
{   
	
	FILE* fp;
	int count;
	char buf[BUFSZ];   
	char command[150];   

	sprintf(command, "ps -ef | grep MainServer | grep -v grep | wc -l" );
	
	while(1)
	{
		if((fp = popen(command,"r")) == NULL)
		{
			err_quit("popen");
		}
		if( (fgets(buf,BUFSZ,fp))!= NULL ) 
		{ 
			count = atoi(buf);   
			if(count  == 0)
			{
				//进程不存在,需要启动
				system("/server/mainserver/MainServer &");
				printf("已经重新拉起!\n");
			}
			else
			{
				//进程存在
				printf("进程存在\n");
			}
		}
		
		usleep(1000000); //1秒
	}

	pclose(fp);   
	return EXIT_SUCCESS;
}

void err_quit(char *msg)
{

	perror(msg);   
	exit(EXIT_FAILURE);   
}

附上守护进程代码:

void set_daemon(){
	int ret_code = fork();
	if (ret_code < 0){
		exit(1);
	}else if (ret_code>0){
		exit(0);
	}
	setsid();
	ret_code = fork();
	if (ret_code < 0){
		exit(1);
	}else if (ret_code>0){
		exit(0);
	}
	chdir(".");
	umask(0);
	for(int fd = 0;fd< getdtablesize();fd++){
		close(fd);
	}
}

int main(int argc, char *argv[])
{
    set_daemon();
    return 0;
}

 


目之所及,皆是回忆,心之所想,皆是过往

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

注册必须使用2-8个中文汉字作为账号