user34537
user34537

Reputation:

Sockets Blocking :( How do i get out?

Here is server code i took from microsoft. Below it is my main which needs to run void important_code(bool);. I have always had this problem when using pipes and sockets on both linux and windows.

How do i exit the select() when i want to quit my app? Assume important_code is always executed on the same thread after the socket code. How would i do that?

I know this is windows code but i get this problem under linux as well

bonus test code: If you comment out main2() in my main function and uncomment the loop you can exit cleanly with ctrl+c. With socket code the blocking select prevents me from doing so. How do i solve this?

#pragma comment(lib, "Ws2_32.lib")
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define DEFAULT_FAMILY  AF_UNSPEC
#define DEFAULT_SOCKTYPE SOCK_STREAM
#define DEFAULT_PORT  "1234"
#define BUFFER_SIZE   23    // length of "WinCE Echo Test Packet"

void Print(TCHAR *pFormat, ...)
{
    va_list ArgList;
    TCHAR Buffer[256];
    va_start (ArgList, pFormat);
    (void)StringCchPrintf(Buffer, 256, pFormat, ArgList);

#ifndef UNDER_CE
    _putts(Buffer);
#else
    printf("%s",Buffer);
#endif

    va_end(ArgList);
}

int main2 ()
{
    SOCKET sock, SockServ[FD_SETSIZE];
    int nFamily = DEFAULT_FAMILY;
    int nSockType = DEFAULT_SOCKTYPE;
    char *szPort = DEFAULT_PORT;
    SOCKADDR_STORAGE ssRemoteAddr;
    int i, nNumSocks, cbRemoteAddrSize, cbXfer, cbTotalRecvd;
    WSADATA wsaData;
    ADDRINFO Hints, *AddrInfo = NULL, *AI;
    fd_set fdSockSet;
    char pBuf[BUFFER_SIZE];
    char szRemoteAddrString[128];

    if(WSAStartup(MAKEWORD(2,2), &wsaData))
    {
        // WSAStartup failed
        return 1;
    }

    sock = INVALID_SOCKET;

    for(i = 0; i < FD_SETSIZE; i++)
        SockServ[i] = INVALID_SOCKET;

    //
    // Get a list of available addresses to serve on
    //

    memset(&Hints, 0, sizeof(Hints));
    Hints.ai_family = nFamily;
    Hints.ai_socktype = nSockType;
    Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;

    if(getaddrinfo(NULL, szPort, &Hints, &AddrInfo))
    {
        Print(TEXT("ERROR: getaddrinfo failed with error %d\r\n"), WSAGetLastError());
        goto Cleanup;
    }

    //
    // Create a list of serving sockets, one for each address
    //

    i = 0;
    for(AI = AddrInfo; AI != NULL; AI = AI->ai_next) 
    {
        if (i == FD_SETSIZE) 
        {
            // getaddrinfo returned more addresses than we could use
            break;
        }

        if((AI->ai_family == PF_INET) || (AI->ai_family == PF_INET6)) // only want PF_INET or PF_INET6
        {
            SockServ[i] = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
            if (SockServ[i] != INVALID_SOCKET)
            {
                if (bind(SockServ[i], AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
                    closesocket(SockServ[i]);
                else 
                {
                    if(nSockType == SOCK_STREAM)
                    {
                        if (listen(SockServ[i], 5) == SOCKET_ERROR)
                        {
                            closesocket(SockServ[i]);
                            continue;
                        }
                    }

                    Print( 
                        TEXT("Socket 0x%08x ready for connection with %hs family, %hs type, on port %hs\r\n"), 
                        SockServ[i], 
                        (AI->ai_family == AF_INET) ? "AF_INET" : ((AI->ai_family == AF_INET6) ? "AF_INET6" : "UNKNOWN"),
                        (AI->ai_socktype == SOCK_STREAM) ? "TCP" : ((AI->ai_socktype == SOCK_DGRAM) ? "UDP" : "UNKNOWN"),
                        szPort);
                    i++;
                }
            }
        }
    }

    freeaddrinfo(AddrInfo);

    if (i == 0) 
    {
        Print(TEXT("ERROR: Unable to serve on any address. Error = %d\r\n"), WSAGetLastError());
        goto Cleanup;
    }

    //
    // Wait for incomming data/connections
    //

    nNumSocks = i;

    FD_ZERO(&fdSockSet);

    for (i = 0; i < nNumSocks; i++)    // want to check all available sockets
        FD_SET(SockServ[i], &fdSockSet);

    if (select(nNumSocks, &fdSockSet, 0, 0, NULL) == SOCKET_ERROR)
    {
        Print(TEXT("ERROR: select() failed with error = %d\r\n"), WSAGetLastError());
        goto Cleanup;
    }

    for (i = 0; i < nNumSocks; i++)    // check which socket is ready to process
    {
        if (FD_ISSET(SockServ[i], &fdSockSet))    // proceed for connected socket
        {
            FD_CLR(SockServ[i], &fdSockSet);
            if(nSockType == SOCK_STREAM)
            {
                cbRemoteAddrSize = sizeof(ssRemoteAddr);
                sock = accept(SockServ[i], (SOCKADDR*)&ssRemoteAddr, &cbRemoteAddrSize);
                if(sock == INVALID_SOCKET) 
                {
                    Print(TEXT("ERROR: accept() failed with error = %d\r\n"), WSAGetLastError());
                    goto Cleanup;
                }

                Print(TEXT("Accepted TCP connection from socket 0x%08x\r\n"), sock);
            }
            else
            {
                sock = SockServ[i];
                Print(TEXT("UDP data available on socket 0x%08x\r\n"), sock);
            }
            break;        // Only need one socket
        }
    }

    //
    // Receive data from a client
    //

    cbTotalRecvd = 0;
    do
    {
        cbRemoteAddrSize = sizeof(ssRemoteAddr);
        cbXfer = recvfrom(sock, pBuf + cbTotalRecvd, sizeof(pBuf) - cbTotalRecvd, 0,
            (SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
        cbTotalRecvd += cbXfer;
    } while(cbXfer > 0 && cbTotalRecvd < sizeof(pBuf));

    if(cbXfer == SOCKET_ERROR)
    {
        Print(TEXT("ERROR: Couldn't receive the data! Error = %d\r\n"), WSAGetLastError());
        goto Cleanup;
    }
    else if(cbXfer == 0)
    {
        Print(TEXT("ERROR: Didn't get all the expected data from the client!\r\n"));
        goto Cleanup;
    }

    if(nSockType == SOCK_STREAM)
    {
        cbRemoteAddrSize = sizeof(ssRemoteAddr);
        getpeername(sock, (SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
    }

    if (getnameinfo((SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize,
        szRemoteAddrString, sizeof(szRemoteAddrString), NULL, 0, NI_NUMERICHOST) != 0)
        strcpy(szRemoteAddrString, "");

    Print(TEXT("SUCCESS - Received %d bytes from client %hs\r\n"), cbTotalRecvd, szRemoteAddrString);

    //
    // Echo the data back to the client
    //

    cbXfer = 0;
    cbXfer = sendto(sock, pBuf, cbTotalRecvd, 0, (SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize);

    if(cbXfer != cbTotalRecvd)
        Print(TEXT("ERROR: Couldn't send the data! error = %d\r\n"), WSAGetLastError());
    else
        Print(TEXT("SUCCESS - Echo'd %d bytes back to the client\r\n"), cbXfer);

Cleanup:

    for(i = 0; i < nNumSocks && SockServ[i] != INVALID_SOCKET; i++)
        closesocket(SockServ[i]);

    if(sock != INVALID_SOCKET)
    {
        shutdown(sock, SD_BOTH);
        closesocket(sock);
    }

    WSACleanup();

    return 0;
}



#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

volatile bool terminate_app=false;
void terminate (int param)
{
    printf("Terminating program...\n");
    terminate_app=true;
}

void important_code(bool v)
{
    printf("Important code here %d\n", v);
}

int main ()
{
    try{
        void (*prev_fn)(int);

        prev_fn = signal (SIGINT,terminate);

        main2();
        //while(terminate_app==false)
        {
        }
    }
    catch(...){
        important_code(1);
    }
    important_code(0);
    return 0;
}

Upvotes: 1

Views: 432

Answers (2)

Ed Heal
Ed Heal

Reputation: 60007

Why make things so complicated with pipes? Surely the exit does not matter if it takes a few seconds. Just put a time out of (say) 3 seconds and check if an exit is required after doing the select.

Will it matter if it takes a few seconds to start the exit process?

Upvotes: 1

ninjalj
ninjalj

Reputation: 43688

On POSIX select() will return on timeout, or when one of the descriptors is ready, or possibly it with return with errno set to EINTR if it's interrupted by a signal.

So, you could use the EINTR behavior. Just install a signal handler with the sigaction() function without the SA_RESTART (restart system calls interrupted by signals) flag. (The behavior of signal() differs between systems, and on some systems it can be changed via #defines).

Or, you could use the self-pipe trick: write to a pipe to signal that you want to exit. If your select() selects the read descriptor for that pipe, it will return.

Upvotes: 2

Related Questions