stdin file descriptor never ready on POLLIN event

59 Views Asked by At

I have a C source code that I intend to port from Linux to Windows. After updating the 'poll' function to 'WSAPoll,' I notice that 'revents' on 'stdin' never becomes ready, causing 'WSAPoll' to block the code due to the absence of ready file descriptors.

How can I ensure that 'stdin' becomes ready in this context?

the client code:

static void start_event_loop(struct client_ctx *cl_ctx)
{
    int nr_ready;

    cl_ctx->need_reload_prompt = true;
    while (1) {
        if (cl_ctx->need_reload_prompt) {
            printf(PLACE_HOLDER);
            fflush(stdout);
            cl_ctx->need_reload_prompt = false;
        }

        #ifndef __WIN32
        nr_ready = poll(cl_ctx->fds, 2, -1);
        #else
        nr_ready = WSAPoll(cl_ctx->fds, 2, -1);
        #endif
        if (nr_ready < 0) {
            if (errno == EINTR)
                continue;

            perror("poll");
            break;
        }

        if (handle_events(cl_ctx) < 0)
            break;
    }
}

static int initialize_ctx(struct client_ctx *cl_ctx)
{
    #ifdef _WIN32
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
        return 1;
    } else
        printf("The Winsock 2.2 dll was found okay\n");
    #endif

    cl_ctx->tcp_fd = connect_server();
    if (cl_ctx->tcp_fd < 0)
        return -1;

    printf("Successfuly connected to %s:%d\n", SERVER_ADDR, SERVER_PORT);

    cl_ctx->fds[0].fd = cl_ctx->tcp_fd;
    cl_ctx->fds[0].events = POLLIN;

    cl_ctx->fds[1].fd = _fileno(stdin);
    cl_ctx->fds[1].events = POLLRDNORM;

    cl_ctx->recv_len = 0;
    memset(&cl_ctx->pkt, 0, sizeof(cl_ctx->pkt));

    return 0;
}

EDIT: The current behavior with 'WSAPoll' is preventing me from inputting or typing anything into 'stdin' because it's blocking the code while waiting for a ready file descriptor.

EDIT2: I recently transitioned from using WSAPoll to WaitForMultipleObjects, but I've encountered an unusual issue. The TCP socket file descriptor never seems to trigger as expected. I've monitored the traffic using Wireshark and confirmed that the packets are being sent from the server to the client. However, in the client program, WaitForMultipleObjects doesn't return the index where the socket file descriptor is stored; instead, it returns the stdin file descriptor. Any insights into what might be causing this unexpected behavior?

The 8787 is server port and the others are client port: wireshark

The complete source code is available in the GitHub repository.

0

There are 0 best solutions below