-1
該代碼需要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'永遠不會被賦值,因此您將未定義的值放入fileids中。關閉後,您永遠不會嘗試恢復原始標準輸出,那麼您爲什麼期望它能夠神奇地工作? – John3136
你的骨骼代碼缺少了很多重要的步驟。它不是一個MCVE([MCVE]),儘管我們可以做出你想做的事情並填寫空白。最好是,如果我們不需要猜測和做鬼臉(例如初始化'fd',或者想知道'out'應該具有什麼意義),並且希望最好。 –
對不起,這還是新的。我做了一些編輯,仍然沒有看到第二個打印聲明,現在我看不到我在終端上輸入的內容。我以爲我用'dup2(fd,1)'恢復了輸出? –