执行叉()时cout vs printf
cout vs printf when doing fork()
我正在尝试使用某些测试程序来理解叉()。我发现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);
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- std::cout.imbue()多重调用
- 数据成员SFINAE的C++17测试:gcc vs clang
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 正在VS调试器中监视映射条目
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- Confusion: decltype vs std::function
- 将IBM Rhapsody模型集成到VS 2019中
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- C++, printf vs cout performance
- 我正在使用 VS 代码,但 cout 不起作用
- 执行叉()时cout vs printf
- Console::WriteLine() vs. cout
- c++ cout vs printf()
- VC++ vs. G++, cout
- Eclipse 悬停在 c++ 中的变量 VS cout 上