Click to See Complete Forum and Search --> : Question about CloseHandle and CreateFile


c0ldshadow
September 22nd, 2006, 04:53 PM
lets say we set HANDLE h to a CreateFile functions return value.

if h==INVALID_HANDLE_VALUE

is it necessary to CloseHandle(h), or is this not needed.

question 2.

before ever calling CloseHandle, is it a good idea to check that the handle does not equal zero? i am wondering if CloseHandle can cause a crash if the handle has an bad value. what are invalid values for CloseHandle? i am thinking i should always make sure a handle is valid before closing it, but i am not sure if this is necessary, and if it is necessary, what the invalid values are for a handle.

thanks for any advice/tips

-c0ldshadow

MrViggy
September 22nd, 2006, 05:08 PM
Well, if it's not a valid handle, then I'd say there's no need to close it. However, I don't think 'CloseHandle(INVALID_HANDLE_VALUE)' will cause a crash. Indeed, it will not:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/closehandle.asp

Viggy

Notsosuperhero
September 22nd, 2006, 05:10 PM
I don't believe it is needed to call CLoseHandle() on an invalid handle. Since CreateFile returns a handle to the file, you would only need to close it when it is a valid handle.

I think, someone please correct me if I'm wrong here.

kirants
September 23rd, 2006, 04:58 PM
I don't believe it is needed to call CLoseHandle() on an invalid handle. Since CreateFile returns a handle to the file, you would only need to close it when it is a valid handle.
I think, someone please correct me if I'm wrong here.
Correct.

greg_dolley
September 23rd, 2006, 09:20 PM
You don't need to call CloseHandle() when the handle value is INVALID_HANDLE_VALUE. In fact, that might cause an exception.

Don't assume any values of the handles, such as zero, always use the Win32 constants. INVALID_HANDLE_VALUE equals -1, not zero.

Greg Dolley

MrViggy
September 25th, 2006, 11:18 AM
You don't need to call CloseHandle() when the handle value is INVALID_HANDLE_VALUE. In fact, that might cause an exception.

Don't assume any values of the handles, such as zero, always use the Win32 constants. INVALID_HANDLE_VALUE equals -1, not zero.

Greg Dolley
No, it will not cause an exception. See the link I posted:
CloseHandle

Closes an open object handle.

BOOL CloseHandle(
HANDLE hObject
);

Parameters

hObject
[in] A handle to an open object. This parameter can be a pseudo handle or INVALID_HANDLE_VALUE.
Viggy