【问题标题】:read file descriptor HANGS读取文件描述符挂起
【发布时间】:2016-04-16 08:44:11
【问题描述】:

我有一个非常简单的源读取文件描述符,它挂起。 有人能注意到代码的问题吗?

第一个是有问题的来源,第二个是在网络上找到的工作来源。两个来源几乎相同。

  • 第一来源

    #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);
    }
    

【问题讨论】:

  • 究竟要做什么来测试这个?
  • 我实现了复制需要读写的文件。为了澄清我的问题并让审阅者更容易看到,我删除了编写代码。

标签: c++ c filesystems system


【解决方案1】:

巧合的是,您正在阅读来自stdin 的内容。这是因为在您的 if(in = ... 中,您放错了一些括号。

发生的情况是首先评估open(argv[1], O_RDONLY)&lt;0,然后将结果放入in。由于open() 的结果不小于零(在成功打开时),in 变为 0。stdin 是文件描述符的名称,它为零(在大多数系统上)。所以它是一个有效的文件描述符,并且 read 很乐意从中读取。它只是没有得到任何东西,直到你在控制台中输入一些东西。

快速修复:

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

【讨论】:

  • 另一个“聪明的代码”复合表达式出错:(由于拆分行会揭示/修复错误,我赞成你发现错误并反对 OP 问题作为另一个令人沮丧的失败调试:(
  • 我不确定这是投反对票的理由,但这绝对是一种学习体验,也许我应该在回答中提到这一点。
  • 啊。愚蠢的错误。在问这个问题之前,我已经在这个代码上工作了将近两个小时。谢谢@David van rijn
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 2012-06-01
  • 2011-08-16
  • 2015-07-04
  • 2015-02-05
相关资源
最近更新 更多