androidfile-descriptorparcelfiledescriptor

Closing a ParcelFileDescriptor file descriptor after detaching


In Android I use the method detachFd from the ParceFileDescriptor to get a file descriptor that I pass to native code for usage. As the file descriptor is detached I close it in native code using fdclose.

Since it is detached, should I still close the ParcelFileDescriptor java instance?

Seems to me that I shouldn't, but I find that in older versions of Android such as Lollipop, StrictMode complains that the resource was not closed, probably because has no idea that it has been detached.

If it is required to close the ParcelFileDescriptor even when the file descriptor has been detached, are there any side effects to be aware of if closed while still using the detached one in native code?


Solution

  • Standard practice, like this:

    try (ParcelFileDescriptor pFd = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_WRITE)) {
        int fd = pFd.detachFd();
    } catch (IOException e) {
    }
    

    Because "ParcelFileDescriptor" and "fd" have been separated, closing the object will not affect "fd".

    // native
    
    close(fd)