从服务 Linux c++ 打开应用程序

Opening an application from service linux c++

本文关键字:应用程序 c++ 服务 Linux      更新时间:2023-10-16

我想从另一个应用程序 B 打开应用程序 A。通过打开它,我不想在 B 中打开它。我发现了许多从另一个应用程序中调用应用程序的方法。但是,我想做的是同时打开另一个(A(。我怎样才能做到这一点?fork(( 和 exec(( 似乎在 B 中打开了 A。我正在为 Linux 和 Mac 开发代码。建议将不胜感激。谢谢。

在进程 A(父进程(中调用fork()以创建进程 A 和进程 B(子进程(

在进程 A 中等待 B 退出...

在进程 B 中,再次调用 fork(((创建 B 和 C(并退出

这会导致 A 收集 B 的状态代码并防止它成为僵尸。

B的退出导致C成为孤儿,成为init的所有者,因此它不再是A的后代。

在进程 C 中,调用 exec 以将当前进程中的程序替换为所需的程序。

像这样:

#include <iostream>
#include <unistd.h>
#include <cassert>
using namespace std;
void forkBtoC()
{
    cout << "B forking" << endl;
    auto child = fork();
    if (0 == child) {
        cout << "C execing" << endl;
        execl("your-program-here", "arg1", "arg2", nullptr);
    }
    else {
    }
}
int main()
{
    // I am parent A
    cout << "A forking" << endl;
    auto result = fork();
    if (result == 0) {
        setsid();
        forkBtoC();
        // I am child B
    }
    else if (result > 0) {
        // I am parent A. result is the pid of B
        int B_code = 0;
        waitpid(result, &B_code, 0);
        cout << "B returned " << B_code << endl;
    }
    else {
        assert(!"failed to fork A");
    }
    return 0;
}