读取文件描述符HANGS

Sea*_*n83 -1 c c++ filesystems system

我有一个非常简单的源读取文件描述符挂起.任何人都可以注意到代码有问题吗?

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

  • 第一来源

    #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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 第二工作源来自网上

    /*
     * ============================================================================
     *  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);
    }
    
    Run Code Online (Sandbox Code Playgroud)

Dav*_*ijn 5

巧妙的巧合,你正在阅读stdin.这是因为if(in = ...你错了一些括号.

发生的事情是首先open(argv[1], O_RDONLY)<0得到评估,并将结果放入in.由于结果open()不小于零(成功打开),因此in变为0.并且stdinfiledescriptor的名称为零(在大多数系统上).所以它是一个有效的文件描述符,阅读非常乐意从中读取.在您在控制台中键入内容之前,它不会得到任何内容.

快速解决:

if ( (in = open(argv[1], O_RDONLY)) < 0) {
Run Code Online (Sandbox Code Playgroud)

  • 另一个"聪明的代码"复合表达式出错了:(因为拆分该行会显示/修复该错误,我正在推测您发现错误并将OP问题视为另一个令人沮丧的失败调试:( (2认同)