[C ++ fork过程,但不作为子过程

问题描述 投票:4回答:1

我有一个命令,该命令提供有关正在运行的进程的诊断信息。我想在进程崩溃之前触发/执行此命令,并将输出捕获到stdout / file。

但是,此命令不能作为它监视的进程的子级运行。该命令正在检测到此情况。它需要分叉为一个单独的父进程。

是否有一种方法可以生成一个新进程,执行命令,但不能作为子进程执行?

c++ linux fork
1个回答
3
投票

这是一个使用我在评论中询问的方法的非常基本的示例:

#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    int result = fork();
    if(result == 0) {
        int fd = open("test", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
        assert(fd >= 0);
        int result = dup2(fd, STDOUT_FILENO);
        assert(result != -1);
        char * const argv[] = {"ls", NULL};
        char * const env[] = { NULL };
        result = execve("/bin/ls", argv, env);
        assert(result != -1);
    }
    return 0;
}

您必须根据需要对其进行调整,但这会将ls的结果存储在文件“ test”中。诀窍是dup2用文件描述符的副本替换了标准输出文件描述符STDOUT_FILENO到我们新打开的文件,因此ls的输出被重定向。

我认为您将能够使用它来获取命令的输出。

© www.soinside.com 2019 - 2024. All rights reserved.