Syntax
BOOL CloseHandle(
HANDLE hObject
);
Parameters
Parameter | Type | Description |
---|---|---|
hObject |
HANDLE |
A handle to an open object. This handle must have been created by an appropriate function such as CreateFile, CreateEvent, or Socket. |
Return Value
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
The CloseHandle
function closes an open object handle. Closing an object handle does not close the object itself. The system closes the object when the last handle to it is closed.
It is important to close handles when they are no longer needed to free up system resources. Failing to close handles can lead to resource leaks and performance degradation.
This function is used to close handles to various types of objects, including:
- Files (CreateFile)
- Events (CreateEvent)
- Mutexes (CreateMutex)
- Semaphores (CreateSemaphore)
- Threads (CreateThread)
- Processes (CreateProcess)
- Sockets (socket)
Example
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hFile = CreateFile(
L"my_document.txt", // File name
GENERIC_READ | GENERIC_WRITE, // Read and write access
0, // Do not share
NULL, // Default security attributes
CREATE_ALWAYS, // Overwrite if exists
FILE_ATTRIBUTE_NORMAL, // Normal file
NULL // No template file
);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Error creating file: %lu\n", GetLastError());
return 1;
}
printf("File handle created successfully.\n");
// ... perform operations on the file ...
// Close the file handle when done
if (CloseHandle(hFile)) {
printf("File handle closed successfully.\n");
} else {
printf("Error closing file handle: %lu\n", GetLastError());
}
return 0;
}
Important Note
Always ensure that you close all handles that are no longer required. This is crucial for maintaining system stability and preventing resource exhaustion.