这是重定向fork和execvp派生的子级的输出的错误方法吗

Is this an incorrect way of redirecting the output of a child spawned by fork and execvp?

本文关键字:输出 错误 方法 派生 重定向 fork execvp      更新时间:2023-10-16

我正在尝试这样做:

int main(int argc, char** argv)
{
    bool foo = false;
    //parse args, check if --foo is an arg, if so mark foo true
    if (foo)
    {
        //child behavior
        while (true) { std::cout << "child" << std::endl; sleep(1); }
    }
    else
    {
        //do some parent process stuff
        pid_t pid = fork();
        if(pid == 0) //spawn child
        {
            char* newArgv[argc+1];
            for (int i = 0; i < argc; ++i) newArgv[i] = argv[i];
            newArgv[argc] = "--foo"; //make child run child code
            std::ostringstream oss;
            oss << argv[0] << " >> foo.txt 2>&1"; //same binary but redir child output
            execvp(out.str().c_str(), newArgv);
        } 
        //more regular parent code
    }
    return 0;
}

因此,基本上,二进制产生了一个新的参数,以不同的方式运行,并且输出被重定向(理想情况下)。不幸的是,虽然这确实产生了两个过程,但我似乎失去了孩子的输出,我不知道为什么?

更简单的有什么问题:

int main(int argc, char** argv) { 
    //do some parent process stuff      
    pid_t pid = fork();
    if(pid == 0) //this is the child
    {
       //child behavior
        while (true) { std::cout << "child" << std::endl; sleep(1); }
    } else {
        //more regular parent code
    }
    return 0;
}

在调用execv之前,必须将文件描述符1设置为指向foo.txt。然后,子进程将使用foo.txt作为标准输出:

fd_t f = open("foo.txt", O_WRONLY);
if (f != 1)
  {
    close(1);
    dup2(f, 1);
    close(f);
  }
execv(...);

上面代码中的任何错误修复都留给读者练习。Bugfixing包括但不限于检查函数调用返回的错误。

编辑:

如果你想让标准错误(过滤器描述符2)出现在标准输出的任何地方,你必须在execv:之前添加它

close(2);
dup2(1, 2);