cfile-iohandleseek

lseek/write suddenly returns -1 with errno = 9 (Bad file descriptor)


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.

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.

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,....);
  }
}

Anybody experience with something similar?

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


Solution

  • 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.

    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.

    Hope this helps.