2016-04-16 135 views
-1

我有一個非常簡單的源讀取文件描述符,其中掛起。 任何人都可以注意到代碼有問題嗎?讀取文件描述符HANGS

第一個是有問題的來源,第二個是在網上找到的工作源。兩個來源幾乎相同。

  • 第一源

    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <unistd.h> 
    #include <fcntl.h> 
    #include <stdio.h> 
    
    int main(int argc, char ** argv) { 
        int n, in; 
        char buf[1024]; 
    
        if ((in = open(argv[1], O_RDONLY)<0)) { 
         perror(argv[1]); 
         return -1; 
        } 
    
        while((n = read(in, buf, sizeof(buf))) > 0) { //HANGS at THIS LINE!!!!!!!!!!! 
         printf("TEST\n"); 
        } 
    
        close(in); 
    
        return 0; 
    } 
    
  • 第二作業源從網上

    /* 
    * ============================================================================ 
    * Name  : sp_linux_copy.c 
    * Author  : Marko Martinović 
    * Description : Copy input file into output file 
    * ============================================================================ 
    **/ 
    
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <fcntl.h> 
    #include <errno.h> 
    #include <sys/types.h> 
    #include <unistd.h> 
    
    #define BUF_SIZE 8192 
    
    int main(int argc, char* argv[]) { 
    
        int input_fd; /* Input and output file descriptors */ 
        ssize_t ret_in; /* Number of bytes returned by read() and write() */ 
        char buffer[BUF_SIZE];  /* Character buffer */ 
    
        /* Create input file descriptor */ 
        input_fd = open (argv [1], O_RDONLY); 
        if (input_fd == -1) { 
         perror ("open"); 
         return 2; 
        } 
    
        /* Copy process */ 
        while((ret_in = read (input_fd, &buffer, BUF_SIZE)) > 0){ 
         printf("TEST\n"); 
        } 
    
        /* Close file descriptors */ 
        close (input_fd); 
    } 
    
+1

究竟你會怎麼做測試呢? –

+0

我實現了複製需要讀寫的文件。爲了澄清我的問題,更容易看到評論者,我刪除了寫代碼。 – Sean83

回答

5

了通過一個有趣的巧合,你是從stdin閱讀。這是因爲在你的if(in = ...中你放錯了一些括號。

發生什麼事情是,首先open(argv[1], O_RDONLY)<0得到評估,並將結果放入in。由於open()的結果不小於零(在成功打開時),因此in將變爲0.而stdin是filedescriptor的名稱,該值爲零(在大多數系統上)。所以它是一個有效的文件描述符,閱讀很快樂。它只是沒有得到任何東西,直到你在你的控制檯輸入東西。

快速修復:

if ((in = open(argv[1], O_RDONLY)) < 0) { 
+2

另一個'聰明的代碼'複合表達式出現錯誤:(因爲拆分行會顯示/修復錯誤,我提高你發現錯誤和降低OP問題作爲又一個令人沮喪的失敗調試:( –

+0

林沒有肯定這就是downvote的理由,但這絕對是一種學習體驗,也許我應該在我的回答中提到這個。 –

+0

啊,愚蠢的錯誤,我在這個代碼上工作了近兩個小時,然後才問這個問題。謝謝@David van RIJN – Sean83