我有一个简单的C语言程序,其中包含读取函数,但是我不理解输出结果。
//code1.c
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
int r;
char c; // In C, char values are stored in 1 byte
r = read ( 0, &c, 1);
// DOC:
//ssize_t read (int filedes, void *buffer, size_t size)
//The read function reads up to size bytes from the file with descriptor filedes, storing the results in the buffer.
//The return value is the number of bytes actually read.
// Here:
// filedes is 0, which is stdin from <stdio.h>
// *buffer is &c : address in memory of char c
// size is 1 meaning it will read only 1 byte
printf ("r = %d\n", r);
return 0;
}
这里是程序运行结果的屏幕截图: 我按照上面的示例运行了这个程序两次,第一次输入"a",第二次输入"aecho hi"。
以下是结果的解释:
- 当调用
read
函数时,它检测到标准输入已关闭,于是重新打开。这一步骤看起来似乎不必要,应该只需读取即可,但为什么会重新打开呢?本人不是很清楚。 - 在bash中输入"aecho hi"并按下回车键。
read
函数优先处理标准输入,并读取了"aecho hi"的第一个字节:"a"。- 通过printf函数确认
read
已经处理了1个字节。 - a.out程序完成并被终止。
- 剩余的数据在bash中被处理,流向标准输出并执行它,但由于
read
函数已经删除了第一个字节,因此导致了问题。
read()
函数时才打开。你的其他解释是正确的。 - alkstdin
不是一个“进程”,而是一个流,就像stdout
一样。 - alkstdin
读取到的内容回显到stdout
,然后执行读取到的内容(echo hi
),并将结果(hi
)打印/写入到stdout
。 - alkread()
被指定为阻塞并等待所需的所有输入(在您的情况下为 1 字节)或直到输入流明确告知:“没有更多输入”,您可以通过控制台(在 UNIX 下)按 Ctrl-D 来执行此操作。闪烁的光标是由 shell 控制的。 - alkecho hi
时,行规则立即将其回显,以便我们可以在终端窗口中看到此行。Shell本身不会执行回显。在OP的示例中也是如此:我们正在输入符号时看到了aecho hi
。但是为什么在./a.out
完成后会出现echo hi
行呢?我的猜测是,如果shell读取带有尾随<enter>
的命令(shell获取echo hi<enter>
进行读取),则会执行回显,否则不会。 - Ilya Loskutov