【发布时间】:2017-02-10 02:22:46
【问题描述】:
此代码获取 2 个文件并将结果放入第三个文件。 它这样做很好,但让我担心的是最后一个 printf 没有打印到屏幕上。第一个打印得很好。这告诉我我没有正确恢复标准输出?
int main (int argc, char *argv[])
{
char *join[4]={"cat", "file1.txt","file2.txt", 0};
int id, fd, status;
printf("fd=%d\n", fd); //this one prints to screen
fd=dup(1); //save stdout
close(1); close stdout
FILE *out=fopen("output.c", "a"); //this is where the output should go
id=fork(); //0 for child
if (id>0) //parent process
{
waitpid(id, &status, WUNTRACED);
}
else if (id==0) //child process
{
execvp(join[0], join);
}
else //error
{
printf("error occured");
}
close(1);
dup2(fd, 1);
fclose(out);
printf("fd=%d\n", fd); //this one doesn't print to screen
return 0;
}
【问题讨论】:
-
fd从未被赋予值,因此您将未定义的值放入文件ID。关闭后,您永远不会尝试恢复原始标准输出,那么您为什么希望它能够神奇地工作呢? -
您的骨架代码缺少很多重要步骤。它不是一个 MCVE (minimal reproducible example),尽管我们可以,差不多,弄清楚你在做什么并填补空白。最好不要对没有完成的事情进行猜测和做鬼脸(例如初始化
fd,或者想知道out应该有什么意义),并希望最好。 -
抱歉,还是新手。我进行了一些编辑,但仍然没有看到第二个打印语句,现在我看不到我现在在终端中输入的内容。我以为我用
dup2(fd, 1)恢复了输出?