c - 为相同的代码获取 2 个输出

标签 c linux unix pipe fork

我使用的是 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/

相关文章:

c - 需要创建一个函数来编码一个单词

ruby - 我如何在 Ruby 中使用 (n)curses?

c - Unix/C - 2 种方法有不同的行为

shell - 使用 shell 脚本在目标中创建与源中相同的目录结构

核心转储,但核心文件不在当前目录中?

C : How can I swap two objects in a array?

c++ - 为什么我看不到 "Application Error"对话框?

linux - 在 Linux/Docker 集群上运行命令

java - 从 Java 执行时,Linux 脚本无法正常工作

mysql - Arch linux 安装mysql access denied报错