简体   繁体   中英

C - Socket TCP - Infinite loop with read

I have a problem when I want to execute two consecutive times the read function Address to retrieve all the data sent by the server.

I read once then read create an infinity loop.

Code :

        char   buff[50] = {0};

        nbytes = 1;
        while (nbytes > 0)
        {
            nbytes = read(m_socket, buff, sizeof(buff));
        }

why read create infinity loop ? is not the "while" the problem.

thank you for your answers.

socket(2) gives you a blocking file descriptor, meaning a system call like read(2) blocks until there's enough some data available to fulfill your request, or end of stream (for TCP) happens (return value 0 ), or some error happens (return value -1 ).

This means you never get out of your while loop until you hit an error, or the other side closes the connection.

Edit 0:

@EJP is thankfully here to correct me, as usual - read(2) blocks until any data is available (not the whole thing you requested, as I initially stated above), including an end-of-stream or an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM