【问题标题】:How to create one level process tree using fork() system call?如何使用 fork() 系统调用创建一级进程树?
【发布时间】:2016-03-04 02:09:34
【问题描述】:

我想使用 fork() 系统调用创建一个一级进程树,如下所示 对于 n = 4 个进程

我已使用以下代码进行了尝试,但这不起作用。 (这里 1 是父进程的子进程)

    for(i = 0 ;i < n; i++){
    chid = fork();
    if ( chid == 0 ){
        printf("%d\n",getpid());
        while(++i < n){
            chid = fork();
            if(chid == 0){
                printf(" %d ",getpid());
                break;
            }
        }
    }
    else
        break;
} 

我怎样才能做到这一点?

【问题讨论】:

  • 1 是父进程吧?
  • 使用单循环并从子进程内部的循环中中断(即 if child == 0)以避免子分叉另一个子进程。
  • @n3rd4n1 no 1 是父进程的子进程

标签: c++ c fork systems-programming


【解决方案1】:
#include<stdio.h>

int main()
{
  int i;
  pid_t  pid;

  for(i=0; i<5; i++)
  {
    pid = fork();
    if(pid == 0)
      break;
  }
  printf("pid %d ppid %d\n", getpid(), getppid());
  if(pid == 0)
  {
    /* child process */
  }
}

根据讨论,这里是修改后的程序。

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

int main()
{
  int i;
  pid_t  pidparent, pid;

  if( (pidparent = fork()) == 0 )
  {
    for(i=0; i<3; i++)
    {
      pid = fork();
      if(pid == 0)
        break;
    }
    if(pid == 0)
    {
      printf("child %d parent %d\n", getpid(), getppid());
    }
  }
  else
  {
    printf("parent %d \n", pidparent);
  }
  /* printf("pid %d ppid %d\n", getpid(), getppid()); */
}

【讨论】:

  • 另外值得注意的是/* child process */块内部i+2与原图中的标签(2,3,4)相同
  • @Michael 有问题,1 也是父进程的子进程。
  • 啊,我假设 1 是父进程。 (看起来这个答案的作者也假设了这一点。)。我想这意味着你只需用 if((pid=fork())==0) { ... } 包装 for 循环
  • 是的,我想我得到了答案。如果创建一个子进程并在该进程内为其余子进程使用此循环,它将正常工作。
  • 我已经添加了修改后的程序。如果有任何问题,请随时发表评论。
猜你喜欢
  • 2021-12-15
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
相关资源
最近更新 更多