int fd1 = open(argv[1],O_RDWR|O_CREAT,0644);
if(fd1 == -1)
{
perror("open file failed\n");
exit(0);
}
int cpFd = dup(STDOUT_FILENO);
if(cpFd == -1)
{
perror("dup failed\n");
exit(0);
}
int newFd = dup2(fd1,STDOUT_FILENO);
if(newFd == -1)
{
perror("dup2 failed\n");
exit(0);
}
printf("dup2 test\n");
printf("...............\n");
close(fd1);
cpFd = dup2(cpFd,STDOUT_FILENO);
if(cpFd == -1)
{
printf("restore failed\n");
exit(0);
}
printf("restore out\n");
代碼如上,思路是使用dup復制一個標準輸出的檔案描述符,然后將標準輸出重定向到一個打開的檔案中,結束后,再使用保存的檔案描述符將標準輸出進行復原。
問題是使用了dup函式過后,所有的printf函式的輸出都到了標準輸出了,沒有重定向到檔案中。如果將printf改為write函式又能成功。不使用dup進行復制的話,那么所有的printf輸出又重定向到了檔案中。
請問是什么原因呢?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/192829.html
標籤:應用程序開發區
下一篇:求助求助
