在for循环中分叉 [英] fork in a for loop

查看:96
本文介绍了在for循环中分叉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码及其行为有疑问:

I have a doubt in the following piece of code and its behaviour:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define N 5
#define nt 1

int pm[N][2],pid[N];
int i,j,size;
char s[100];
int count=0;

int main()
{
 for(i=1;i<N;i++)
    {
      printf("\n i=%d",i);

      if(pid[i]=fork() == -1)
        {
          printf("\n fork not wrking");
          exit(1);
        }
      else if(pid[i]>0)
        {
          printf(" \n pid:%3d\n",pid[i]);
        break;
        }

    }
return 0;
}

我最初认为代码将产生一个进程并跳过循环. 从而,
1产生2并跳出.
2产生3并跳出
3产生4个并跳过
4产生5并跳出.

I initially thought that the code will spawn a process and skip out of the loop. Thereby,
1 spawns 2 and skips out.
2 spawns 3 and skips out
3 spawns 4 and skips out
4 spawns 5 and skips out.

我尝试执行此代码,但对我得到的答案感到惊讶(对于代码中i的printf).这是输出

I tried executing this code and was surprised by the answer i got ( for the printf of i in the code). Here is the output

 i=1
 i=2
 i=3
 i=2
 i=4
 i=3
 i=3
 i=3
 i=4
 i=4
 i=4
 i=4
 i=4
 i=4
 i=4

任何人都可以向我解释一下这是怎么回事. 注意:我正在使用Solaris计算机.

Can Anyone please explain to me what is going on here. NOTE: I am working on a Solaris machine.

推荐答案

更新

在更新的代码中缺少一组括号.应该是if ((pid[i] = fork()) == -1)而不是if (pid[i] = fork() == -1)

由于优先规则,后者等效于if (pid[i] = (fork() == -1)).最终,每次在循环中每次给pid[i]分配0,因此父母认为它们是子进程,因此不会脱离循环.

The latter is equivalent to if (pid[i] = (fork() == -1)) due to precedence rules. It ends up assigning 0 to pid[i] each time through the loop, so the parents think they are child processes and don't break out of the loop.

我同意您对应该发生的情况的分析.父母应该生一个孩子然后退出,因此每个i=n打印输出应该只显示一次.

I agree with your analysis of what should happen. The parent should spawn a child and then quit, so each i=n printout should only show up once.

确定输入的密码完全与问题中指定的相同吗?我运行了您的程序(进行了少量修改),并得到了您预测的输出:

Are you sure you typed it in exactly as specified in your question? I ran your program (with minor modifications) and got the output you predicted:

$ cat fork.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define N 5

int main() {
    int pid[N], i;

    for(i=1;i<N;i++) /* What’s the total number of processes? */
    {
    printf("i=%d\n",i); // Output of all the is
    if((pid[i]=fork())==-1) exit(1);
    else if(pid[i] > 0) break;
    }

    return 0;
}
$ gcc -o fork fork.c
$ ./fork
i=1
i=2
$ i=3
i=4

请注意,我将打印输出中的\n移到了末尾.当您将其放在行的开头时,最后将不刷新stdout,因此,当父进程和子进程都刷新其输出缓冲区时,您将获得多个打印输出.那可能是造成您问题的原因.在Mac上的FWIW中,每个打印输出都有两次.

Note that I moved the \n in the printout to the end. When you put it at the beginning of the line you end up with stdout not being flushed, so you get multiple printouts when the parent and child processes both flush their output buffers. That might be the cause of your problem. FWIW on my Mac I got each printout twice.

这篇关于在for循环中分叉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆