C++ 在父级内存中处理它。这个怎么样(用其他文件替换/dev/null)@JerryJeremiah谢谢。但在演示代码中,重定向涉及子进程…@aschepler是的,将子进程的扩展流重定向到实际文件。但是在子进程中运行的bin文件不能修改,所以父进程是否可以控制

C++ 在父级内存中处理它。这个怎么样(用其他文件替换/dev/null)@JerryJeremiah谢谢。但在演示代码中,重定向涉及子进程…@aschepler是的,将子进程的扩展流重定向到实际文件。但是在子进程中运行的bin文件不能修改,所以父进程是否可以控制,c++,linux,C++,Linux,在父级内存中处理它。这个怎么样(用其他文件替换/dev/null)@JerryJeremiah谢谢。但在演示代码中,重定向涉及子进程…@aschepler是的,将子进程的扩展流重定向到实际文件。但是在子进程中运行的bin文件不能修改,所以父进程是否可以控制子进程的重定向?类似system(“./qualcommbinary>out.txt”)的东西是否足够?小修正:O_CREATE应该是O_CREATE我相信您还需要使用STDOUT\u FILENO、STDERR\u FILENO而不是STDO


在父级内存中处理它。这个怎么样(用其他文件替换/dev/null)@JerryJeremiah谢谢。但在演示代码中,重定向涉及子进程…@aschepler是的,将子进程的扩展流重定向到实际文件。但是在子进程中运行的bin文件不能修改,所以父进程是否可以控制子进程的重定向?类似system(“./qualcommbinary>out.txt”)的东西是否足够?小修正:O_CREATE应该是O_CREATE我相信您还需要使用STDOUT\u FILENO、STDERR\u FILENO而不是STDOUT,直接使用stderr。@XavierLeclercq谢谢,修复了那些(加上缺失的#包括)。小修复:O#u CREATE应该是O#u CREATE我相信你还需要使用STDOUT_文件号,stderr#u文件号,而不是直接使用STDOUT,stderr。@XavierLeclercq谢谢,修复了那些(加上缺失的#包括)。
#include <cstdlib>
extern "C" {
#include <fcntl.h>
#include <unistd.h>
}
#include <stdexcept>
#include <iostream>

pid_t start_child(const char* program, const char* output_filename)
{
    pid_t pid = fork();
    if (pid < 0) {
        // fork failed!
        std::perror("fork");
        throw std::runtime_error("fork failed");
    } else if (pid == 0) {
        // This code runs in the child process.
        int output_fd = open(output_filename, O_WRONLY | O_CREAT | O_TRUNC);
        if (output_fd < 0) {
            std::cerr << "Failed to open log file " << output_filename << ":"
                      << std::endl;
            std::perror("open");
            std::exit(1);
        }
        // Replace the child's stdout and stderr handles with the log file handle:
        if (dup2(output_fd, STDOUT_FILENO) < 0) {
            std::perror("dup2 (stdout)");
            std::exit(1);
        }
        if (dup2(output_fd, STDERR_FILENO) < 0) {
            std::perror("dup2 (stderr)");
            std::exit(1);
        }
        if (execl(program, program, (char*)nullptr) < 0) {
            // These messages will actually go into the file.
            std::cerr << "Failed to exec program " << program << ":"
                      << std::endl;
            std::perror("execl");
            std::exit(1);
        }
    }
    return pid;
}