叉子工作很奇怪

时间:2018-09-12 10:08:32

标签: c printf fork

我在大学锻炼。

  

创建一个声明变量的程序   n,派生一个新进程并打印“ Hello   来自父项[PID-n]”和“来自   父母子女的子女[PID-n]”   流程。运行10次   并解释输出

我写了这段代码

#include <stdio.h>
#include <sys/types.h>

void main()
{
    pid_t n = getpid();
    printf("Hello from parent [PID - %d], n);
    fork();
    n = getpid();
    printf("Hello from child [PID - %d], n);
}

但是在编译和执行后,我得到了这个

Hello from parent [PID - 10135]Hello from child [PID - 10135]Hello from parent [PID - 10135]Hello from child [PID - 10136]

“您好,父母...”打印了两次。但是,如果我要稍微更改代码printf语句

#include <stdio.h>
#include <sys/types.h>

void main()
{
    pid_t n = getpid();
    printf("Hello from parent [PID - %d]\n, n);
    fork();
    n = getpid();
    printf("Hello from child [PID - %d]\n, n);
}

(我刚刚在每个字符串中添加了“ \ n”) 我会得到

Hello from parent [PID - 10223]
Hello from child [PID - 10223]
Hello from child [PID - 10224]

它可以正常工作。我已经尝试使用-std = c99标志使用cc和gcc,但是结果保持不变。

我认为这个问题在printf函数的某个地方)

所以,请解释一下发生了什么,为什么会这样工作。

1 个答案:

答案 0 :(得分:1)

这是因为stdout正在缓冲数据,并且仅在到达换行符时才刷新数据。 因此,当您没有在父级第一次打印中添加换行符时,实际上并没有打印出换行符,而是在进程中进行了缓冲。然后在退出进程(父进程或子进程)时刷新缓冲区。

请参阅 Why does printf not flush after the call unless a newline is in the format string?

了解更多详情。