【问题标题】:Fork function with 2 integers具有 2 个整数的 fork 函数
【发布时间】:2021-12-31 00:27:58
【问题描述】:

我正在尝试了解 fork() 函数如何适用于我的操作系统类别。

enter image description here

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 写道:要像您描述的那样创建一个二维流程网格,您需要第二个循环,但它不应该嵌套

标签: c fork


【解决方案1】:

break; 语句是一个无条件跳出包含循环的语句。因此,内部循环中的(第一个)break; 将终止内部循环(在第一次迭代中),并且循环中的任何代码都不会执行。所以你的分叉循环完全等同于:

for (i = 0; i < height; i++) {
    fork();
}

内部循环永远不会到达增量和第二次迭代,所以还不如不存在。 t 值永远不会在任何地方使用,因此也可能不存在。

这种循环最终会生成 2height 进程,包括原来的父进程。通过循环的每次迭代,到目前为止创建的所有进程都将分叉,使进程总数翻倍。


要创建 n 个进程,最简单的方法是循环 n 次分叉,然后在两个进程之一中 break;(只是父进程或子进程。类似于:

for (i = 1; i < height; i++)   // starting at 1 as we want to count the existing parent process
    if (fork() == 0) break;

这里父母会创建一个孩子然后跳出循环,每个孩子会再创建一个孩子然后打破,最后一个孩子会正常完成循环(而不是创建孩子)。

要创建像您描述的流程的 2D 网格,您需要第二个循环,但它应该嵌套。在图片中创建第一列后,每个进程都应创建一行:

for (i = 1; i < width; i++)
    if (fork() > 0) break;

这里的“父级”进程(原始父级或在第一个循环中创建的任何子级)将直接创建所有子级 - 除了第一个列之外的任何列中的子级都不会创建任何子级。

请注意,为了清洁,您应该检查 fork() 是否曾经失败(返回 -1),尽管大多数时候您所能做的就是报告错误。

【讨论】:

  • 您好,多德,感谢您的回答。我一直在努力寻找问题的答案,但仍然存在一些我完全不了解的关于循环和分叉的问题。我重新制作了原始问题以进一步澄清它。
猜你喜欢
  • 2012-09-27
  • 2020-09-10
  • 2016-10-28
  • 1970-01-01
  • 2020-10-01
  • 2012-04-29
  • 2021-01-11
  • 2019-04-30
  • 1970-01-01
相关资源
最近更新 更多