Click to See Complete Forum and Search --> : Stop a TCP thread.


Victor Kulichkin
December 8th, 2004, 03:32 AM
Hi all,

Help me to solve a problem with stop of TCP thread. Sorry for my bad English, but I try to describe the problem here.
I moved a standard Whois client routine from Linux to my Windows dialog app. I run it by a thread:

BOOL m_flagStop;
FILE *m_whois_in;

void CWhois::OnOK()
{
……………
m_flagStop = FASLE;
AfxBeginThread(ThreadWhois, this);
}

UINT ThreadWhois(LPVOID param)
{
sockaddr dest;
socklen_t destlen;
…….
// here I open a socket
SOCKET fd = WSASocket(dest.sa_family, SOCK_STREAM, 0, NULL, 0, 0);
WSAConnect(fd, &dest, destlen, NULL, NULL, NULL, NULL);
…….
//here I bind <fd> with a stream
fd = _open_osfhandle (fd , _O_TEXT);
m_whois_in = _fdopen(fd, "r");

…….
//getting info from a remote Internet server
char buf[1024];
while(1)
{
if (m_flagStop == TRUE)
goto End;
if (fgets(buf, sizeof(buf), m_whois_in) == NULL)
{
…..
//Error
goto End;
}
//here I display info from <buf> to a dialog window
// after it check for end of receiving
…..
}
}

The program works well when my Internet channel is not busy. However, when the channel has big loading, I get hanging on the while (1) cycle. For it I created the “Stop” button, which has to break this cycle:

void CWhois::OnButtonStopWhois()
{
….
m_flagStop = TRUE;
}

This code did not solve a problem. The program hung up when it was waiting for info from a remote server on the command fgets(buf, sizeof(buf), m_whois_in).

I tried to go out of this situation by the function ungetc():

void CWhois::OnButtonStopWhois()
{
….
m_flagStop = TRUE;
ungetc((int)'\n', m_whois_in);
}

But it also did not help. In this case this function did not work because the stream was locked by fgets().

Any ideas!!! Help!

JonaChong
December 8th, 2004, 04:22 AM
How about closing the stream in your stop function:

void CWhois::OnButtonStopWhois()
{
fclose(m_whois_in);
m_whois_in = NULL;
}

Andreas Masur
December 8th, 2004, 04:24 AM
[ Moved thread ]

Mathew Joy
December 9th, 2004, 02:47 AM
What OS are you using? Socket handles are treated as file handles in Unix, but not in win 9x and lower. Though socket handles can be treated as file handles in Win NT and above, it is not often prefered because some transport service providers may not support it. It is hard to tell the behavior of fgets() and co. in relation to recv() and co. So my suggestion is to rewrite the whole thing using standard socket functions (one that uses wsock 1.1 lib). It is not hard though, (much easier compared to other codes).

Another thing that is said over and over again in this forum is you have to check the return values of the socket functions and see if the call has been successfull. If it is not handle it by calling WSAGetLastError() (You get the error no).