【问题标题】:How to get pid of some process started inside child process with help if exec family in C/C++ in linux?如果 linux 中的 C/C++ 中的 exec 系列,如何在子进程中启动某些进程的 pid?
【发布时间】:2021-07-22 11:11:24
【问题描述】:

我想获取某个进程的 pid(我们称之为 Somebinary),它是在子进程内部的 exec 家族的帮助下启动的,并假设 Somebinary 一旦启动就永远不会停止。我想从父进程打印这个进程的pid。

我不能在父进程中等待,因为子进程将通过 exec* 启动 Somebinary 并且永远不会停止。我知道我能做到:

int start(std::string Somebinary){
    pid_t childpid = fork();
    if(childpid == 0){
        freopen(logfile.c_str(), "a+", stdout);
        dup2(1, 2);

        exec*("/bin/sh", "sh", "-c", Somebinary.c_str(), " &", NULL)
        exit(1);
    }
    // print pid of Somebinary from here
    return 0;
}

但如果可能的话,我想减少额外的开销。

基本上,我想像在 C/C++ 中的 bash 中那样做以下事情:

重击

$ Somebinary > logfile 2>&1 &
$ pidof Somebinary

我知道我可以在子进程中借助 freopen 和 dup2 进行标准输出和标准错误重定向。但剩下的就是疑问了。

P.S.:这必须在 Linux 中完成

非常感谢您的帮助。

【问题讨论】:

  • 请在exec之前显示其余代码。你有fork 电话吗?基本上你可以在调用exec 之前fork 以便父进程可以从fork 结果中获取子进程pid。这是通常的做法。
  • 是的,我在执行之前确实有 fork,我将编辑代码以包含该部分。 @kaylum
  • childpid 已经是子 pid。你还需要/想要什么? exec 不会更改 pid。它替换进程而不是创建一个新进程。
  • 哦,这是否意味着 Somebinary 的 pid 将是 childpid? @kaylum
  • 它是childpid。为什么你认为这是不同的东西?正如我所说,exec 不会更改 pid。

标签: c++ linux exec


【解决方案1】:

请注意,exec 不会“创建进程”或更改 PID,fork 会。

正如@kaylum 所说,childpid 已经是执行进程的 PID。你可以打印它:

int start(std::string Somebinary){
    pid_t childpid = fork();
    if(childpid == 0){
        freopen(logfile.c_str(), "a+", stdout);
        dup2(1, 2);

        exec(Somebinary.c_str(), NULL);
        exit(1);
    }
    if (childpid < 0) { // basic error handling
        perror("fork"); return -1;
    }
    // print pid of Somebinary from here
    printf("childpid = %jd\n", (intmax_t) childpid);
    return 0;
}

另外你可能想直接绕过/bin/shexecSomebinary,否则你会得到/bin/sh的PID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多