Read from socket

后端 未结 5 1021
遥遥无期
遥遥无期 2020-12-31 10:08

I need to read from an AF_UNIX socket to a buffer using the function read from C, but I don\'t know the buffer size.

I think the best way is to read

5条回答
  •  囚心锁ツ
    2020-12-31 10:28

    One way to read an unknown amount from the socket while avoiding blocking could be to poll() a non-blocking socket for data.

    E.g.

    char buffer[1024];
    int ptr = 0;
    ssize_t rc;
    
    struct pollfd fd = {
       .fd = sock,
       .events = POLLIN
    };
    
    poll(&fd, 1, 0); // Doesn't wait for data to arrive.
    while ( fd.revents & POLLIN )
    {
       rc = read(sock, buffer + ptr, sizeof(buffer) - ptr);
    
       if ( rc <= 0 )
          break;
    
       ptr += rc;
       poll(&fd, 1, 0);
    }
    
    printf("Read %d bytes from sock.\n", ptr); 
    

提交回复
热议问题