简体   繁体   中英

Which argument of write() sys-call is evaluated in an if block when the number of bytes are written either into standard input or standard output

Which argument of write() sys-call is evaluated in an if block when the number of bytes are written either into standard input or standard output. In the following example (from the Beginning Linux Programming);

if(write(1, "Here is some data\n", 18) != 18)
    write(2, "Write error in file descriptor 1\n", 46);

I tried to make the if statement false by making the string longer/shorter than 18 bytes but still it prints the string "Here is some data". The second write statement is evaluated only when I change the third argument from 18 to 17 or 19. It seems the if condition is evaluated only by the third argument as it shouldn't be the case. Please help me understand it.

The first call:

write(1, "Here is some data\n", 18)

is always executed. When number of written characters are not 18 (corresponds to "!= 18" from the code), also the second call is executed:

write(2, "Write error in file descriptor 1\n", 46);

I think you're trying to ask a different question, but I'm not sure what it is. The answer currently is: all of them.

All arguments to write have to be evaluated, so the function can be called, so the comparison can be made.

What I'm guessing you may be asking is: why doesn't changing the string length change the number of bytes written. That's because C will happily let you read past the end of your string. If you specify that 18 bytes are to be sent, 18 will be sent, whether that means sending only part of the string, or reading some garbage behind the "\\n" to make it 18.

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