考虑以下代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int i;
for(i = 0; i < 2; i++)
{
fork();
printf(".");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序输出8个点.怎么可能呢?不应该有6个点吗?
我试图使用一些测试程序来理解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
有人能解释一下吗?谢谢