我有一个关于以下两个代码的问题,第二个代码是" \ n"对我有意义,因为fork()将调用child来执行fork之后的任何操作,但是,第一个代码对我来说没有意义。第一次只执行print111 print222两次,为什么会这样?子进程是否应该在fork之前省略任何代码?
int main()
{
//pid = fork();
printf("11111");
printf("22222");
int pid;
pid = fork();
if (pid == 0)
printf("Hello, I'm Child\nAnd my pid is %i \n", pid);
else
printf("Hello, I'm Parent\nAnd my pid is %i \n",pid);
}
输出
1111122222Hello, I'm Parent
And my pid is 2076
1111122222Hello, I'm Child
And my pid is 0
int main()
{
//pid = fork();
printf("11111\n");
printf("22222\n");
int pid;
pid = fork();
if (pid == 0)
printf("Hello, I'm Child\nAnd my pid is %i \n", pid);
else
printf("Hello, I'm Parent\nAnd my pid is %i \n",pid);
}
输出
11111
22222
Hello, I'm Parent
And my pid is 2091
Hello, I'm Child
And my pid is 0