gpt4 book ai didi

c - 这种行为是由标准定义的吗?

转载 作者:行者123 更新时间:2023-12-04 10:30:06 25 4
gpt4 key购买 nike

#include <unistd.h>
int main(int argc, char* argv[])
{
char buf[500];
read(0, buf, 5);
return 0;
}

上面的stdin读取 5个字符,但是如果我输入多于5:

12345morethan5
[root@ test]# morethan5
-bash: morethan5: command not found

其余字符将作为 shell 命令执行。

这种行为有标准定义吗?

最佳答案

有点:-)

您的程序读取 5 个字符,仅此而已。不多也不少。其余部分保留在终端缓冲区中,并在您的 C 程序终止后发送到您的 shell。

由于您使用的是 read(),这是一个原始系统调用,而不是任何 C stdio 缓冲替代方案,因此这种行为不仅是预期的,而且是必需的 .

来自 read() 上的 POSIX 标准:

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.

...

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the st_atime field of the file, and shall return the number of bytes read. This number shall never be greater than nbyte.

...

Upon successful completion, read() [XSI] [Option Start] and pread() [Option End] shall return a non-negative integer indicating the number of bytes actually read.

read() 应该从不从文件描述符中读取比请求更多的字节。

来自related part在终端上:

It is not, however, necessary to read a whole line at once; any number of bytes, even one, may be requested in a read() without losing information.

...

The last process to close a terminal device file shall cause any output to be sent to the device and any input to be discarded.

注意:通常情况下,您的 shell 仍会为终端打开一个文件描述符,直到您结束 session 。

关于c - 这种行为是由标准定义的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6549507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com