繁体   English   中英

读取文件描述符HANGS

[英]read file descriptor 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); } 

碰巧的是,您正在从stdin中阅读。 这是因为在if(in = ...您放错了一些括号。

正在发生的事情是,第一open(argv[1], O_RDONLY)<0被评价,并且将结果得到投入in 由于结果open()不小于零(上succesfull开放), in变为0并且stdin是它是一个零(在大多数系统)的文件描述符的名称。 因此,它是一个有效的文件描述符,从中读取数据非常高兴。 直到您在控制台中键入内容,它什么都没有。

快速解决:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM