我使用的是 linux\unix 操作系统。当我运行下面的代码时,我得到 2 个输出。下面提到:
a) 12345- b) 1-2-3-4-5-
谁能告诉我上述两个输出的原因和方式吗?
int main()
{
int i, n, pfds[2];
char c, buf[80];
pipe(pfds);
if (fork() == 0)
{
for (c='1'; c<='5'; c++)
write(pfds[1], &c, 1);
}
else
{
close(pfds[1]);
while ((n = read(pfds[0], buf, sizeof(buf))) > 0)
{
write(1, buf, n);
write(1, "-", 1);
}
}
return 0;
}
最佳答案
Linux 会将您的写入缓冲到管道中,并在某个时刻刷新缓冲区,并且读取叉会一次性读取所有内容。您应该能够通过在写入后执行 fflush() 来更改此设置。
关于c - 为相同的代码获取 2 个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40758681/