簡體   English   中英

即使在使用 dup2/dup 之后,C 程序也會打印到終端而不是文件

[英]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
}

我嘗試過的其他事情:

  1. 更改打開文件的權限(添加O_RDWR
  2. 在 2 台單獨的 PC 上運行 - 我主要在遠程桌面上運行 linux 的 uni pc,但也在筆記本電腦上安裝了 VMware。
  3. 嘗試在dup2上使用close + dup組合
  4. 嘗試使用帶有perror的條件來查看是否有任何步驟會提示我為什么它不起作用。
  5. 嘗試對 output 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM