The system call write(fd, buf, len) may return 0 when len > 0?
From manual given here
On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.
So it says that write can return value > 0 if actually write something.
Yes it may return zero. When the calling of that function will not write any thing then it will return the value zero.
From man
page of write
zero indicates nothing was written
if ( len > 0 )
This condition is for checking the given bytes are totally written or not. This condition is for totally write the given bytes when no problem occurs in write function.
len
is 1000
, first time write is write write the bytes as 512
, but we need to write the 100 bytes to that file descriptor. So that we have to subtract the value of written bytes.
len -= written;
Now len
have the value 488(1000-512)
. Now in next loop, write have to write the 488 bytes.
buf += written;
this is for we have written the 512 bytes. We have to write the remaining bytes so for that we have incrementing that pointer position to point out the remaining bytes.
( written == 0 )
It is for whether the above write function is write something or not. If it doesn't write anything then close for that.
As per your update, the above concept will more useful when we are writing into pipes,FIFO,and stream or network devices. In normal file descriptor it may not make any effect.
This will happen for normal file descriptor , when the file system runs out of space or we hit our quota limit. This condition is rare. This concept is mainly for writing into other than normal file descriptors.
In this case, no.
From man 2 write
:
RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.
Due to the while(len > 0)
condition, write()
writes zero bytes if and only if it encounters an error, in which case it will return -1.