简体   繁体   English

如何使用fork()系统调用创建一级进程树?

[英]How to create one level process tree using fork() system call?

I want to create a one level process tree using fork() system call, which looks as follows for n = 4 process 我想使用fork()系统调用创建一个一级进程树,对于n = 4进程如下所示

在此处输入图片说明

I have tried this with the following code but this is not working. 我已经尝试使用以下代码对此进行了尝试,但这不起作用。 (here 1 is a child of parent process ) (这里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;
} 

How can I make this ? 我该怎么做?

#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 */
  }
}

Based on the discussion, here is the modified program. 根据讨论,这是修改后的程序。

#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()); */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM