When does the write() system call write all of the requested buffer versus just doing a partial write?

后端 未结 3 666
无人及你
无人及你 2021-02-09 21:55

If I am counting on my write() system call to write say e.g., 100 bytes, I always put that write() call in a loop that checks to see if the length that gets returned is what I e

3条回答
  •  灰色年华
    2021-02-09 22:38

    write may return partial write especially using operations on sockets or if internal buffers full. So good way is to do following:

    while(size > 0 && (res=write(fd,buff,size))!=size) {
        if(res<0 && errno==EINTR) 
           continue;
        if(res < 0) {
            // real error processing
            break;
        }
        size-=res;
        buf+=res;
    }
    

    Never relay on what usually happens...

    Note: in case of full disk you would get ENOSPC not partial write.

提交回复
热议问题