开发者

linux: stdin causes select to return when I don't want it to

开发者 https://www.devze.com 2023-03-18 10:55 出处:网络
I have a problem with select returning when there is something on stdin, even though I don\'t want it to. For example here is a code that is meant to wait for data on a socket for a certain amount of

I have a problem with select returning when there is something on stdin, even though I don't want it to. For example here is a code that is meant to wait for data on a socket for a certain amount of time, however if there is data on stdin, select returns:

int mylib_UDP_Client_Recv(int sock, void *data, int max_length, int timeout)
//timeout is taken to be milliseconds
{
    struct sockaddr_in sdata;
    struct timeval timeouts;

    timeouts.tv_sec = timeout / 1000;
    timeout -= timeouts.tv_sec * 1000;
    timeouts.tv_usec = timeout * 1000;

    int n;
    int maxfd = sock;
    fd_set static_rdset, static_wrset, rdset, wrset;
    unsigned int datalen = sizeof(struct sockaddr_in);

    FD_SET(sock,&static_rdset);
    FD_SET(sock,&static_wrset);


    rdset = static_rdset;
    wrset = static_wrset;
    if (selec开发者_Python百科t(maxfd+1,&rdset,NULL,&wrset,&timeouts) == 0) //wrset used as exception set
    {
        return -1; //timed out
    }
    if (FD_ISSET(sock,&rdset))
    {
        n = recvfrom(sock,data,max_length,0,(struct sockaddr *)&sdata,&datalen);
        if (n < 0) return 0;
        return n;
    }
    else
    {
        return 0; //error
    }
}


You never use FD_ZERO() on any of your fd_sets. FD 0 (stdin) is probably set, along with various other random FDs.

0

精彩评论

暂无评论...
验证码 换一张
取 消