gnustep/libs-base

Unexpected and incorrect behaviour of NSFileHandle closeFile and fileDescriptor

wlux opened this issue · 2 comments

wlux commented

I was a bit shocked and surprised to learn that NSFileHandle's closeFile method raises an exception when it is called for an already closed handle. Closing a closed file handle is obviously a redundant operation, but I cannot think of a reason why this would be considered an error (and I don't seem to be alone with that opinion – for almost any library that I've used so far, including Apple's own Foundation, closing a closed file handle is just a no-op).
Lacking an official means to check whether a file handle is closed, raising an exception when a file handle is closed twice means that a client application that wants/needs to close file handles prematurely needs to keep track on its own whether is has closed a particular file handle already or not even though NSFileHandle already does that bookkeeping (if only to raise that exception). On GNUstep, one could possibly use the fileDescriptor method to check whether a file handle is closed, as it returns -1 after the handle was closed. However, this
a) isn't documented,
b) I don't know whether it would work on Windows or not and one would have to rely on the result of nativeHandle instead, and
c) most importantly, it doesn't work with Apple's Foundation, where fileDescriptor raises an exception (and is documented to do so) when called for a closed file handle.

wlux commented

Just adding a simple test case below.
On macOS (Sonoma), the program generates this output

File descriptor = 3
Closing file twice succeeds
Cannot get file descriptor of closed handle: *** -[NSConcreteFileHandle fileDescriptor]: unknown error

while for GNUstep I got this:

2024-06-10 11:09:46.784 CloseHandle[222497:222497] File descriptor = 3
2024-06-10 11:09:46.786 CloseHandle[222497:222497] Closing file twice raises exception: <NSException: 0x1883fe8> NAME:NSFileHandleOperationException REASON:attempt to close closed file INFO:(null)
2024-06-10 11:09:46.786 CloseHandle[222497:222497] File descriptor after closing = -1

main.m.txt

rfm commented

Fixed that some time ago, but forgot to close this issue.