执行叉()时cout vs printf

cout vs printf when doing fork()

本文关键字:cout vs printf 执行      更新时间:2023-10-16

我正在尝试使用某些测试程序来理解叉()。我发现Cout和printf()之间的不同行为:

程序1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
    printf("Hi , %dn" , getpid());
    fork();
    return 0;
}

我得到:

HI,9375

HI,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;
}

我得到:

hi,7277

两个程序之间的唯一区别是第一次使用printf()在第二次使用cout

时打印输出

任何人都可以解释吗?谢谢

使用stdio时,stdout将完全缓冲,除非它写入终端;写入终端时,它的线缓冲。

因此,如果将输出重定向到文件或管道的程序1运行程序1,则printf将行写入输出缓冲区,但不会冲洗缓冲区。当过程分叉时,在两个过程中都重复缓冲区。当他们退出时,每个人都会冲洗自己的缓冲区副本,该副本打印了线。

如果您写的话,您将在程序2中获得相同的结果:

cout << "Hi , " <<getpid() << "n";

但是endl除了输出Newline字符外,还可以冲洗缓冲区。程序1中的等效内容是:

printf("Hi , %dn" , getpid());
fflush(stdout);