When is FileDescriptor closed?

别来无恙 提交于 2019-12-19 04:13:16

问题


My app needs to do the following:

  • Open a FileInputStream, and obtain the underlying FileDescriptor (via getFd())
  • Create new FileInputStream objects based on the above FileDescriptor

So far, I only needed one FileDescriptor, so I used to close it by calling close() on the original stream (i.e. on the stream which getFd() I called). I use it because some Android API methods have such a parameter.

Now that I will have more FileInputStream objects at the same time, when will the FileDescriptor be closed? (My guess: when all FileInputStream objects are closed?)


回答1:


I belive you are right. A small test shows that the FileDescriptor becomes invalid after its FileInputStream is closed. Note that, in case of more than one FileInputStream for the same FileDescriptor, the FileDescriptor becomes invalid as soon as its first FileInputStream is closed, i.e. it does not matter if you close first fis1 and then fis2 or the other way around:

FileInputStream fis1 = new FileInputStream("/tmp/adb.log");
FileDescriptor fd = fis1.getFD();
FileInputStream fis2 = new FileInputStream(fd);
System.out.println(fd.valid());
fis1.close();
System.out.println(fd.valid());
fis2.close();
System.out.println(fd.valid());

Output is:

true
false
false

Do not forget to close the stream in a finally block, to make sure you close it also in case of an I/O (read/write) error.



来源:https://stackoverflow.com/questions/17263278/when-is-filedescriptor-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!