本文介绍了在C你如何重定向标准输入/输出作出execvp()或类似的电话时/标准错误的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的code:
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_FILENO
, STDOUT_FILENO
和 STDERR_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()或类似的电话时/标准错误的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!