Linux 下实现进程退出后自动重启

 

Linux 下实现进程退出后自动重启 一般方案有2 1.采用脚本,网上很多,但对一些嵌入式系统因资源限制,大部分命令裁剪了,故不可行 2.采用fork,父进程等待子进程退出

一下采用fork 方法实现,对于重启多个进程, 可采用(pid = waitpid( -1, &status, WNOHANG))避免多个进程同时重启导致僵尸进程

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

#include <string>
using namespace std;

static const char* FULL_NAME= "/usr/bin/server";
static const char* PROGRAM = "server";

static void StartProcess(std::string &name, std::string ¶m)
{
	int i = 2;
	char tmp[200], *argv[32];
	const char *delim=" ";
	memcpy(tmp, param.c_str(), 200);
	argv[0] = ( char * ) name.c_str();
	argv[1] = strtok( ( char * ) tmp, delim);
	while ( (argv[i++] = strtok(NULL, delim) ));
	argv[i] = NULL;

	int status = 0;
	string cmd = "killall ";
	cmd += PROGRAM;

	while (true)
	{
		
		int r = system(cmd.c_str());
		if (r!=0)
		{
			printf("WatchDog system err=%d:%s
",errno,strerror(errno));			
		}
		pid_t pid = fork();
		if (pid < 0)
		{
			printf("WatchDog fork err=%d:%s
",errno,strerror(errno));
			sleep(5);
			continue;
		}
		if (pid == 0)
		{
			printf("[WatchDog] StartProcess %s ok!
",name.c_str());
			execvp(argv[0], argv);
			exit( -1);
		}
		printf("[WatchDog] chirend pid=%d ok!
",pid);

		if (pid>0)
		{
			pid_t exitPid = wait(&status);
			printf("[WatchDog] pid=%d exitPid=%d!
",pid,exitPid);
			sleep(5);
		}		
	}	
}

int main(int argc,char** argv)
{
	string name = FULL_NAME;
	string param;

	StartProcess(name,param);
	
	return 0;
}


经验分享 程序员 微信小程序 职场和发展