c - 在 C 中,如何在进行 execvp() 或类似调用时将 stdin/stdout/stderr 重定向到文件?

标签 c linux unix exec io-redirection

我有以下代码:

pid_t pid = fork();
if (pid == -1)
{
    // ...
}
else if (pid == 0)
{
    stdin = someopenfile;
    stdout = someotherfile;
    stderr = somethirdopenfile;
    execvp(args[0], args);
    // handle error ...
}
else
{
    // ...
}

问题是,execvp() 调用的输入/输出仍然是控制台,而不是文件。显然我做错了什么,正确的方法是什么?

最佳答案

正确的方法是使用 dup2 将文件描述符 STDIN_FILENOSTDOUT_FILENOSTDERR_FILENO 替换为打开的文件()。您还应该关闭子进程中的原始文件:

else if (pid == 0)
{
    dup2(fileno(someopenfile), STDIN_FILENO);
    dup2(fileno(someotherfile), STDOUT_FILENO);
    dup2(fileno(somethirdopenfile), STDERR_FILENO);
    fclose(someopenfile);
    fclose(someotheropenfile);
    fclose(somethirdopenfile);
    execvp(args[0], args);
    // handle error ...
}

关于c - 在 C 中,如何在进行 execvp() 或类似调用时将 stdin/stdout/stderr 重定向到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543443/

相关文章:

c - 为什么允许递归会使 C 在 8 位 CPU 上变慢/效率低下

linux - 如何在字符串之前将分配给变量的文本插入到文件中

c - 在 child 运行时用 fork 做某事

linux - 使用 awk 计算并打印每行的平均分数

c - gmp 值转换为 char*

c - 将文件中的随机名称分配给结构名称

c - 交换链表中的节点

linux - 无法在 VirtualBox 中安装 CentOS

java - 即使在服务器停止后仍然能够访问 url?

c++ - GCC 规范文件 : how to get the installation path