Using accept() and select() at the same time?

前端 未结 3 577
余生分开走
余生分开走 2020-12-14 08:18

I\'ve got an event-driven network server program. This program accepts connections from other processes on other hosts. There may be many short-lived connections from diff

3条回答
  •  被撕碎了的回忆
    2020-12-14 08:48

    you could use listen then use select or poll then accept

    if (listen(socket_fd, Number_connection) < 0 )
    {
        perror("listen");
        return 1;
    }
    fd_set set;
    struct timeval timeout;
    int rv;
    FD_ZERO(&set); /* clear the set */
    FD_SET(socket_fd, &set); /* add our file descriptor to the set */
    
    timeout.tv_sec = 20;
    timeout.tv_usec = 0;
    
    rv = select(socket_fd + 1, &set, NULL, NULL, &timeout);
    if (rv == -1)
    {
        perror("select"); /* an error occurred */
        return 1;
    }
    else if (rv == 0)
    {
        printf("timeout occurred (20 second) \n"); /* a timeout occurred */
        return 1;
    }
    else
    {
        client_socket_fd = accept (socket_fd,(struct sockaddr *) &client_name, &client_name_len);
    }
    

提交回复
热议问题