Linux下创建两个子进程,并在子进程异常退出时重新创建

直接上代码,看注释即可:

#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>

using namespace std;

static int s_hmi_pid = -1;          // hmi进程id
static int s_data_process_pid = -1; // DataProcess进程id
static int s_recreate_count = 0;    // 子进程创建次数统计

// 启动HMI
void run_hmi()
{
    char* argv[] = { "hmi", NULL };

    const char* path = "/home/hccloud/Desktop/printArgs";
    execv(path, argv);
}

// 启动DataProcess
void run_data_process()
{
    char* argv[] = { "data_process", NULL };

    const char* path = "/home/hccloud/Desktop/printArgs";
    execv(path, argv);
}

int main(/*int argc, char *argv[]*/)
{
start:
    printf("start !\n");
    if (s_hmi_pid == -1) // 防止重复创建
    {
        // fork 子进程
        s_hmi_pid = fork();
        if (s_hmi_pid == 0)
        {
            run_hmi();
            return 0; //子进程退出后返回
        }
        printf("hmi pid: %d\n", s_hmi_pid);
    }

    if (s_data_process_pid == -1) // 防止重复创建
    {
        // fork 子进程
        s_data_process_pid = fork();
        if (s_data_process_pid == 0)
        {
            run_data_process();
            return 0; //子进程退出后返回
        }
        printf("data_process pid: %d\n", s_data_process_pid);
    }

    int status = 0; // 子进程退出状态
    int pid = 0;
    while (s_recreate_count < 6) // 重新创建次数判断
    {
        pid = waitpid(-1, &status, WNOHANG); // 获取子进程状态
        printf("waitpid: %d !\n", pid);
        if (pid == s_hmi_pid && status != 0) // 如果子进程hmi异常退出,则重新创建
        {
            s_hmi_pid = -1; // 重设标志位,使其回到start处时可以重新创建
            s_recreate_count ++;
            goto start;
        }

        if (pid == s_data_process_pid && status != 0) // 如果子进程DataProcess异常退出,则重新创建
        {
            s_data_process_pid = -1; // 重设标志位,使其回到start处时可以重新创建
            s_recreate_count ++;
            goto start;
        }
        sleep(1); //
    }

    wait(NULL); // 等待子进程全部结束

    cout << "Hello World!" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hccloud/article/details/79289116