使用分叉时的输出窗口

Output window when using Fork

本文关键字:输出 窗口 分叉      更新时间:2023-10-16

以下代码的输出是什么:

void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */
int main(void)
{
 pid_t pid; //stores the process ID
 pid = fork(); //creates a child process of same program
 if (pid == 0)
 ChildProcess(); //If a child is executing a process,for it , PID will be 0
 else
 ParentProcess(); //The parent can have access to child process PID
return 0;
}

void ChildProcess(void)
{
 for(int i=0; i< 100; i++)
    cout<<"I am the child"<<endl;
}
void ParentProcess(void)
{
for(int i=0; i< 100; i++)
 cout<<"I am the father"<<endl;
}

子进程和他的父进程在同一输出控制台(窗口)上打印输出?!我的意思是输出是这样的:我是父亲我是孩子我是父亲我是孩子我是父亲我是孩子

是的,它们输出到同一个控制台,所以你应该得到:

I am the child
I am the father
I am the child
I am the father
I am the child
I am the father
I am the child
I am the father
...

但你也可以有这样的东西:

I am the father
I am the child
I am the child
I am the child
I am the father
I am the father
...

顺序高度依赖于操作系统、计算机的内核数量,并且可能是非常随机的。