Is there a cleaner way to use the write() function reliably?

前端 未结 4 1757
悲哀的现实
悲哀的现实 2021-02-09 16:15

I read the man pages, and my understanding is that if write() fails and sets the errno to EAGAIN or EINTR, I may

4条回答
  •  温柔的废话
    2021-02-09 16:43

    You have a bit of a "don't repeat yourself" problem there - there's no need for two separate calls to write, nor for two nested loops.

    My normal loop would look something like this:

    for (int n = 0; n < count; ) {
        int ret = write(fd, (char *)buf + n, count - n);
        if (ret < 0) {
             if (errno == EINTR || errno == EAGAIN) continue; // try again
             perror("write");
             break;
        } else {
            n += ret;
        }
    }
    
    // if (n < count) here some error occurred
    

提交回复
热议问题