【发布时间】:2021-12-31 00:27:58
【问题描述】:
我正在尝试了解 fork() 函数如何适用于我的操作系统类别。
int main(int argc, char *argv[])
{
int i, height, width;
if (argc!= 3) exit(0);
height = atoi(argv[1]); /* height */
width = atoi(argv[2]); /* width */
pid_t t;
for(i=0;i<height;i++){
t=fork();
for(int j=0;j<width;j++){
if(j==width-1){
if(t!=0){
break;
}
//break;
} else if (t==0){
//continue;
}}}
printf("I´m father %d and my child is %d\n", getppid(), getpid());
sleep(1);
return 0;
}
这是我在 height=4 和 width=3 时得到的结果。
I am the father 3182 y mi hijo es 3184 and my t value = 3190
I am the father 3180 and my child is 3181 and my t value = 3191
I am the father 2008 and my child is 3180 and my t value = 3186
I am the father 3180 and my child is 3182 and my t value = 3187
I am the father 3181 and my child is 3188 and my t value = 3192
I am the father 3180 and my child is 3183 and my t value = 3189
I am the father 3181 and my child is 3185 and my t value = 3194
I am the father 3185 and my child is 3193 and my t value = 3195
I am the father 3180 and my child is 3182 and my t value = 3187
I am the father 3180 and my child is 3181 and my t value = 3191
I am the father 2008 and my child is 3180 and my t value = 3186
I am the father 3181 and my child is 3185 and my t value = 3194
I am the father 2008 and my child is 3180 and my t value = 3186
I am the father 3180 and my child is 3181 and my t value = 3191
I am the father 2008 and my child is 3180 and my t value = 3186
在线课程老师发布了一条消息,提示我尝试遵循,“情况是树会从初始过程开始向下 x=height 级别,每个级别的第一个孩子将有 y=宽度的孩子,除了在最后一层会有 (witdh -1) 孩子” 我 100% 确定必须有 2 个 for 循环,一个用于高度的外循环和一个用于宽度的内循环。所有的孩子都从这两个循环中出来并在创建后终止,除了最后一个,即当 j == width - 1 时,它会继续外部循环(高度)的另一次重复。没有任何指导和线索是什么。 谢谢。
我在使用 fork 方面非常新手,所以如果有人可以帮助我 提前致谢。
【问题讨论】:
-
首先让他们打印他们的号码。
-
@Jorge Pulido Lozano - 即使在 Chris Dodd 写道:要像您描述的那样创建一个二维流程网格,您需要第二个循环,但它不应该嵌套?