fork 和 execve 应用程序中的一些按顺序 condition_variable 和其他同时

fork and execve applications some of them in order with condition_variable and the others simultaneously

我正在尝试使用 fork() 和 execve() 执行多个应用程序。 其中一些相互依赖。 因此,例如,我想让它同时执行 A、B、C 并让它等到 B in "Running" status before execute C 当场景如下。

applications
A
B-C   (C depends on B)
D

第一次。我想出了如下非常原始的解决方案。 fork 并执行 app 并等待其状态更改为 运行 状态。 (应用程序具有初始状态,一切就绪,它发送消息 它处于 运行 状态至 state_mgr)

// app_starter.cpp
CreateAppProcess(...) {
   ...
   child = fork();
   ...
   if (child == 0) {
      execve(name, argv, argc);
      ...
   }
   ...
}


StartApplication(AppInstance& app) {
...
    CreateAppProcess(app->name, app->argv, app->argc);
...
}

这样使用函数"StartApplication()"。

//app_starter.cpp

// 1. declare AppInstance array.
AppInstance app_array[10];  
// 2. set AppInstances in the array.
...
// 3. start apps
for (int i = 0 ; i < 10; i++) {
   StartApplication(app_array[i]);
}

// 4. wait until "execve"d app is on Running state.
for (int i = 0; i < 1000000000; i++) 
{
    return_value = app_ins.GetAppState(app->name);
    if(return_value == State::Running) break;
}

上面的解决方案存在三个问题。

  1. 它一次只能执行一个应用程序。
  2. 应该等到上一个应用程序处于 "Running" 状态,即使它不是依赖项。
  3. for 循环不断消耗资源重复执行 GetAppState()。

所以我试图一个一个地解决问题,但我坚持第一个解决方案 3。 - condition_variable。

// app_instance.cpp
std::condition_variable g_app_cv;
std::mutex g_app_cv_mtx;
...
ReceiveAppStateMsg() {
    while(_quit) {
        ret_ = mq_receive(rcv_handler, buffer, size_, 0);
        ...
        if (msg_rcvd == State::Running) {
            ...
            g_app_cv.notify_one();
        }
    }
}

//app_starter.cpp
extern std::condition_variable g_app_cv;
extern std::mutex g_app_cv_mtx;

// 1. declare AppInstance array.
AppInstance app_array[10];  
// 2. set AppInstances in the array.
...
// 3. start apps  - change for loop to condition_variable.
for (int i = 0 ; i < 10; i++) {
   StartApplication(app_array[i]);
}

// 4. wait until "execve"d app is on Running state.
{
    std::unique_lock<std::mutex> lk(g_app_cv_mtx);
    g_app_cv.wait_for(lk, std::chrono::milliseconds(1000));
}

总而言之,我需要一些关于...的见解

  1. 如何跨多个 cpp 文件使用 condition_variable。

  2. 使用 std::condition_variable.

    的 fork() 和 exec() 的正确方法
    • 想知道我的解决方案是否正确。
  3. 如何同时或没有太多延迟地 fork() 和 exec()。

execution order timeline I want
start --- |end
--------------
 A----|
  B----|C----|
   D----|
--------------

感谢您阅读这么长的问题。

您需要在进程之间的共享内存区域中分配互斥锁和条件变量。您还需要将 mutex 和 cond vars 的属性设置为 PTHREAD_PROCESS_SHARED

如何共享内存:link

但是,出于与您类似的目的,我更愿意编写一个小的进程生命周期模块(完全构建在使用域套接字的 IPC 之上)。您可以将流程的生命周期分为:INIT、运行、ALIVE、STOPPED、DEAD(根据您想要做什么,我只是给您提供线索)。一旦您的流程到达其生命周期中的某个阶段,您就可以发布一个事件通知该阶段。另一个进程可以只是等待在合作进程中实现该状态。一个简单的心跳机制就可以确定另一个进程是 ALIVE 还是 Dead。其他阶段可以通过 IPC 发布通知(首选域套接字)