gpt4 book ai didi

c - fork() 在循环中从哪里执行?

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:27 30 4
gpt4 key购买 nike

考虑下面的代码,在 for 循环中的 fork() 之后程序将从哪里开始执行?我无法理解输出。

 #include <stdio.h>                                                                                 
#include <sys/types.h>

int parent_code() {
printf("[%d] Parent\n",getpid());
}

int child_code() {
printf("[%d] Child\n",getpid());
}

int main() {
int i;
pid_t pid;

for(i=0;i<4;i++) {
pid = fork();
if(pid == 0) {
child_code();
} else {
parent_code();
waitpid(pid,&i,0);
}
}
}

输出:

[4896] Parent
[4897] Child
[4897] Parent
[4898] Child
[4898] Parent
[4899] Child
[4899] Parent
[4900] Child
[4898] Parent
[4901] Child
[4897] Parent
[4902] Child
[4902] Parent
[4903] Child
[4897] Parent
[4904] Child
[4896] Parent
[4905] Child
[4905] Parent
[4906] Child
[4906] Parent
[4907] Child
[4905] Parent
[4908] Child
[4896] Parent
[4909] Child
[4909] Parent
[4910] Child
[4896] Parent
[4911] Child

更新

  1. 子程序从哪里开始执行?

  2. 如果从顶部开始,是否会出现 fork 炸弹( child 再次调用 fork )?所以在这个程序中,我希望子进程从 if(pid == 0) { 行开始执行,我只需要一个父进程和 4 个子进程。我这样做哪里出错了?

最佳答案

理解fork 系统调用的一种简单方法是将其视为返回两次 的函数。它在父进程中返回一次,就像普通函数一样,然后在新进程中返回一次。这两个进程在 fork“返回”的地方继续。

I want only one parent process and 4 child process. Where have I gone wrong in doing that

想想第一个子进程。它调用 child_code() 然后它自己 fork 。所以如果 children 可以通过循环,他们也会 fork 。防止这种情况发生的一种简单方法是在 child_code 之后调用 break

关于c - fork() 在循环中从哪里执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26583738/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com