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

前端 未结 3 501
余生分开走
余生分开走 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);
    }
    
    0 讨论(0)
  • 2020-12-14 08:48

    I'd put a listener in separate process(thread) not to mess things up. And run a worker process on another to handle existing sockets. There's no need for non-blocking listener really. And no thread overhead running 2 threads.

    It should work like that: you accept on your listener thread till it returns you a descriptor of client socket and pass it to worker which is doing all dirty read/write job on it.

    If you want to listen several ports and don't want to hold one process per listener I suggest you set your socket in O_NONBLOCK and do someth like:

    // loop through listeners here and poll'em for read
    // when read is successful call accept, get descriptor,
    // pass it to worker and continue listen
    while(1){
        foreach( serverSocket in ServerSockets ){
             if( serverSocket.Poll( 10, SelectRead ) ){
                  clientSocket = serverSocket.Accept();
                  // pass to worker here and release
             }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 08:52

    Last time I checked, you could just listen on a socket and then select or poll to see if a connection came in. If so, accept it; it will not block (but you may want to really should set O_NONBLOCK just to be sure)

    0 讨论(0)
提交回复
热议问题