在 C 中,如何在进行 execvp() 或类似调用时将 stdin/stdout/stderr 重定向到文件? [英] In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?

查看:34
本文介绍了在 C 中,如何在进行 execvp() 或类似调用时将 stdin/stdout/stderr 重定向到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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() 调用的输入/输出仍然是控制台,而不是文件.显然我做错了什么,正确的做法是什么?

The problem is, the input/output of the execvp() call is still the console, rather than the files. Clearly I am doing something wrong, what is the right way to do this?

推荐答案

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

The right way to do it is to replace the file descriptors STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO with the opened files using dup2(). You should also then close the original files in the child process:

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 中,如何在进行 execvp() 或类似调用时将 stdin/stdout/stderr 重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆