简体   繁体   English

当将字节数写入标准输入或标准输出中时,在if块中评估write()系统调用的哪个参数

[英]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. 当将字节数写入标准输入或标准输出时,在if块中计算write()系统调用的哪个参数。 In the following example (from the Beginning Linux Programming); 在下面的示例中(来自Linux编程入门);

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". 我试图通过使字符串长于或短于18个字节来使if语句为false,但仍然打印字符串“ 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. 仅当我将第三个参数从18更改为17或19时,才对第二个write语句求值。似乎if条件仅由第三个参数求值,因为事实并非如此。 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: 当写入的字符数不是 18(对应于代码中的“!= 18”)时,还将执行第二个调用:

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. 这是因为C会很乐意让您阅读字符串末尾的内容。 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. 如果您指定要发送18个字节,则将发送18个字节,这意味着仅发送字符串的一部分,还是读取“ \\ n”后面的一些垃圾使其成为18。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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