How to exit connect () blocking call in Windows?

Is there a way to get out of a blocking call connect()in Windows?

Please note that I do not want to switch to non-blocking sockets.

+4
source share
1 answer

According to MSDN connect page :

Note When you issue a blocking Winsock call, such as connect , Winsock may have to wait for the network event to complete the call. Winsock makes an emergency wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another Winsock blocking call within APC that interrupted the current Winsock blocking call in the same thread will result in undefined behavior and should never be attempted by Winsock clients.

So, if you want to cancel the call connect, you must do this from another thread:

/* apc callback */
VOID CALLBACK apc( _In_ ULONG_PTR data)
{
    /* warning, some synchronization should be added here*/
    printf("connect canceled by APC\n");
}

/* second thread code */
DWORD WINAPI cancel_thread_function(void* main_thread_handle)
{       
    /* wait 500 ms*/
    Sleep(500);

    if (test_if_connect_is_still_pending())
    {
        /* cancel connect */
        QueueUserAPC(apc, (HANDLE)main_thread_handle, (ULONG_PTR) NULL);
    }
    return 0;
}



/* The thread in which is executed the connect call */
HANDLE mainThread;
DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mainThread, 0, TRUE, DUPLICATE_SAME_ACCESS);

/* create cancelation thread */
CreateThread(NULL, 0, cancel_thread_function, , 0, NULL);

/* Warning: I should close the handles... */

connect(...);

IMO, EJP solution is the best (non-blocking connectand testing with select).

+3
source

Source: https://habr.com/ru/post/1670751/


All Articles