问题
There is a SafeHandleZeroOrMinusOneIsInvalid
class in the .NET Framework, as well as a SafeHandleMinusOneIsInvalid
class.
Why is this? In which situations is zero ever a valid handle?
回答1:
As additional lecture to the other answers, see this OldNewThing blog entry about inconsistent handle return values.
回答2:
Yes. Zero is file handle for stdin. Non-kernel handles aren't valid if zero.
回答3:
As put forth by Microsoft in their documentation (and demonstrated in description by Joshua,) it is implementation dependant, so to speak:
It describes the format of an invalid handle.
For example, some handles use -1 as an invalid handle value, while others use 0. Further derivations of this class (for example, file or registry handles) can specialize this further. See the SafeFileHandle class for an example of a class that derives from SafeHandleZeroOrMinusOneIsInvalid.
回答4:
I think you're reading too much into the name: all this means is that some APIs by convention return 0 to indicate failure, others return -1. For an API that returns -1, this doesn't mean that 0 will ever be a valid handle, just that the API returns -1 to indicate failure.
So this is really about the value that is typically used by an API to indicate failure; it doesn't say anything about whether any other handle values are valid or not for any given set of APIs.
来源:https://stackoverflow.com/questions/7715480/is-zero-ever-a-valid-handle