[英]C program prints to terminal instead of file even after using dup2/dup
我正在學習操作系統課程,並在 Linux 上使用 C 完成作業。 在其中一項任務中,我應該將 output 重定向到一個文件,但由於某種原因,我一直在終端中獲取 output。 我嘗試編寫一個簡單的程序來做到這一點,但它仍然沒有工作:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
}
我嘗試過的其他事情:
O_RDWR
)dup2
上使用close
+ dup
組合perror
的條件來查看是否有任何步驟會提示我為什么它不起作用。STDOUT_FILENO
而不是 1非常感謝您對此的任何幫助!
stdio 通常將 output 緩沖到stdout
- 它在連接到終端時是行緩沖的,在連接到文件時是完全緩沖的。 由於您沒有編寫任何換行符,因此在任何一種模式下都不會自動刷新緩沖區。 當程序退出時,緩沖區會自動刷新,此時它會寫入 FD 1 連接到的最后一個 stream。
使用setvbuf()
關閉緩沖,或者在printf()
調用之間顯式刷新 output。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
fflush(stdout);
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
fflush(stdout);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.