【问题标题】:What is bad file descriptor in c?什么是c中的坏文件描述符?
【发布时间】:2010-10-21 15:12:21
【问题描述】:

这是我想要读取文件的函数代码:

int sendByByte(int filed,int sockfd,int filesize)
{
 int i=0;
 int sent=0;
 char buf[BUFSIZE];
 while(i<filesize)
 {
  printf("fd is : %d\n",filed);
  printf("i: %d\n",i);
  int byte_read=read(filed,buf,BUFSIZE);
  if(byte_read == -1)
  {
   printf("MOSHKEL dar read\n");
   return -1;
  }
  int byte_send=send(sockfd,buf,byte_read,0);
  if(byte_send==-1)
  {
   printf("MOSHKEL dar send\n");
   return -1;
  }
  close(filed);
  i+=byte_read;
  sent+=byte_read;
 }
 return sent;
}

问题是当i=0 工作并读取文件但随后read() 返回-1。 代码有什么问题?

  • socketfd => 服务器的套接字
  • filed => 文件描述符

我确定文件描述符是有效的。

【问题讨论】:

  • 欢迎来到 SO。这个问题与 C 本身无关,文件描述符是一种操作系统特性。请相应地更改您的问题的标题和标签。

标签: c posix file-descriptor


【解决方案1】:

在第一次迭代后close(filed)(第 22 行),导致所有进一步的读取失败。 将close 调用移到循环之外,甚至更好:让调用者关闭文件描述符,因为他打开了它。

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2013-03-20
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2019-07-01
    • 2015-06-08
    • 2016-10-19
    相关资源
    最近更新 更多