执行fork()时cout vs printf

che*_*glg 3 c++ printf fork cout

我试图使用一些测试程序来理解fork().我发现cout和printf()之间有不同的行为:

计划1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int main()
{
    printf("Hi , %d\n" , getpid());
    fork();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

嗨,9375

嗨,9375

计划2:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int main()
{
    cout << "Hi , " <<getpid() << endl;
    fork();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

嗨,7277

两个程序之间的唯一区别是第一次使用printf()时打印输出cout

有人能解释一下吗?谢谢

Bar*_*mar 11

使用时stdio,stdout除非写入终端,否则完全缓冲; 当写入终端时,它是行缓冲的.

因此,如果运行程序1并将输出重定向到文件或管道,则printf将该行写入输出缓冲区,但不会刷新缓冲区.当进程分叉时,缓冲区在两个进程中都是重复的.当它们退出时,它们都会刷新缓冲区的副本,从而打印出该行.

如果你写的话,你会在程序2中得到相同的结果:

cout << "Hi , " <<getpid() << "\n";
Run Code Online (Sandbox Code Playgroud)

但是endl,除了输出换行符之外,还会刷新缓冲区.计划1中的等价物是:

printf("Hi , %d\n" , getpid());
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)