It reports An invalid handle was specified.
for the code below:
if(hPipe)
CloseHandle(hPipe);
What can I do?
It reports An invalid handle was specified.
for the code below:
if(hPipe)
CloseHandle(hPipe);
What can I do?
This implies that either hPipe
is not initialized to a valid pipe handle, or it was valid but has already been closed. Double check your logic related to this variable.
if (hPipe != INVALID_HANDLE_VALUE && hPipe != 0)
CloseHandle(hPipe);
INVALID_HANDLE_VALUE is -1, not 0, so you can't just do if(hPipe). 0 is also an invalid handle value, so you can't just check against INVALID_HANDLE_VALUE and be done. Don't you love win32?
I suspect you have something like this:
class SmartPipe
{
HANDLE hPipe;
public:
//Functions which do something to hPipe
~SmartPipe()
{
if (hPipe)
CloseHandle(hPipe);
}
};
The problem is that when SmartPipe
is created, hPipe is initialized to random garbage. You have to initialize it yourself. Add hPipe to an initializer list in your class:
class SmartPipe
{
HANDLE hPipe;
public:
SmartPipe() : hPipe(0)
{
}
//Functions which do something to hPipe
~SmartPipe()
{
if (hPipe)
CloseHandle(hPipe);
}
};
If this is not your scenario, at least check that hPipe
is getting initialized somewhere, even if the value it is being set to is 0.
EDIT: This is a double free scenario:
class SmartPipe
{
//As above
};
void SomeFunc(SmartPipe input) //Note pass by value
{ //At this point, the pipe object was copied
//2 SmartPipes are alive with the same handle value here.
//Do something with `input`
}
int main()
{
SmartPipe input;
//setup input somehow
SomeFunc(input);
//Note that at this point the pipe passed by value has already been
//destroyed, and the handle held by `input` has already been closed.
} //`input` destroyed here, resulting in a double free.
Solve that by making SmartPipe
noncopyable, or writing copy constructors and copy assignment operators for it which copy the handle (Using something like DuplicateHandle
), or reference counting.