I have a small application that redirects the stdout/in of an another app (usually command prompt or bash for windows). The problem is that if the connection is interrupted the my process has no idea and it never closes because of this line:
WaitForSingleObject(childProcess.hThread, INFINITE)
I was thinking of having a loop with something like this:
while(true)
{
if(ProcessIsDead(childProcess.hThread))
// close socket and exit
if(SocketIsDisocnnected(hSocket))
// close process and exit
}
What functions would I use to accomplish this? For ProcessIsDead I know there is a winapi for getting the exit code but I don’t know how to check if the socket is disconnected without calling recv (which i cant do)
Note: I’m assuming the connected socket is communicating over a network link, because I’m not sure how it would become disconnected if it were a local pipe, except by one process or the other dying.
Use the select() function in the socket API to query the read status of the socket. select() will tell you the socket is “readable” if any of the following is true:
So, if select() says that the socket is readable, it is safe to call recv(), which will give you WSACONNRESET or return 0 bytes if the connection was reset or closed respectively. select() takes a ‘timeout’ parameter, which you can set to an appropriate time interval or zero if you want to poll the socket state.
Information on the select() function is at http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx