lseek/write突然返回-1,errno = 9(错误的文件描述符) [英] lseek/write suddenly returns -1 with errno = 9 (Bad file descriptor)

查看:961
本文介绍了lseek/write突然返回-1,errno = 9(错误的文件描述符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用lseek()寻找想要写入数据的位置. 使用open()成功打开了文件,并且我的应用程序能够多次使用lseek()write().

My application uses lseek() to seek the desired position to write data. The file is successfully opened using open() and my application was able to use lseek() and write() lots of times.

在给定的时间,对于某些用户并且不容易重现,lseek()返回-1,其errno为9.在此之前文件未关闭,并且文件句柄(int)未被重置.

At a given time, for some users and not easily reproducable, lseek() returns -1 with an errno of 9. File is not closed before this and the filehandle (int) isn't reset.

此后,将创建另一个文件; open()可以,并且lseek()write()可以再次使用.

After this, another file is created; open() is okay again and lseek() and write() works again.

更糟糕的是,该用户再次尝试了完整的序列,一切都很好.

To make it even worse, this user tried the complete sequence again and all was well.

所以我的问题是,操作系统是否可以出于某种原因为我关闭文件句柄? 是什么原因造成的?文件索引器或某种类型的文件扫描器?

So my question is, can the OS close the file handle for me for some reason? What could cause this? A file indexer or file scanner of some sort?

解决此问题的最佳方法是什么?伪代码是最好的解决方案吗? (不要介意代码布局,将为其创建函数)

What is the best way to solve this; is this pseudo code the best solution? (never mind the code layout, will create functions for it)

int fd=open(...);
if (fd>-1) {
  long result = lseek(fd,....);
  if (result == -1 && errno==9) {
      close(fd..); //make sure we try to close nicely
      fd=open(...);

      result = lseek(fd,....);
  }
}

有人有类似经历吗?

摘要:对于给定的fd,文件查找和写入工作正常,并且突然无故返回errno = 9.

Summary: file seek and write works okay for a given fd and suddenly gives back errno=9 without a reason.

推荐答案

我不知道您使用的是哪种类型的设置,但是在以下情况下,我认为会产生这种效果(或其他类似的效果).我尚未对此进行验证,因此请带一点盐.

I don't know what type of setup you have, but the following scenario, could I think produce such an effect (or else one similar to it). I have not tested this to verify, so please take it with a grain of salt.

如果将要打开的文件/设备实现为服务器应用程序(例如NFS),请考虑如果服务器应用程序关闭/重新启动/重新启动会发生什么.文件描述符虽然最初在客户端有效,但可能不再映射到服务器端的有效文件句柄.可以想象,这可能导致一系列事件,其中客户端将获得EBADF.

If the file/device you are opening implemented as a server application (eg NFS), consider what could happen if the server application goes down / restarts / reboots. The file descriptor though originally valid at the client end might no longer map to a valid file handle at the server end. This can conceivably lead to a sequence of events wherein the client will get EBADF.

希望这会有所帮助.

这篇关于lseek/write突然返回-1,errno = 9(错误的文件描述符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆