如何在递归函数中使用fork?

时间:2014-02-14 23:37:25

标签: c unix recursion fork

我正在尝试编写一个递归程序,以便使用fork构建一个进程树。我想我会根据级别数和子项数正确构建树。但是,当我想要退出时,我继续在树上建造,我超过了孩子和水平的数量,因此我最终没有正确退出。

这是我的代码和示例输入和输出。请注意,需要在命令行参数中指定子级数和级别数。

代码:

    #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <errno.h>
int level;
static void run_process(const char *child, int lev)
{
   fprintf(stderr, "ALIVE: Level %d process with pid= %ld child of ppid=%ld\n",
           lev, (long)getpid(), (long)getppid());
}

int fork_level (int l, int c){
int i;
pid_t rightchild;


 if (l>=level){

 fprintf(stderr, "Exiting: Level %d with pid= %ld, child of ppid= %ld\n",l,  (long)getpid(),    (long)getppid());
    exit (1) ;  
 }
 else {

    for (i=0; i<c; i++){
     if ((rightchild = fork()) < 0)
       {   
           fprintf(stderr, "can't fork, error %d\n", errno);
           return 0;
       }
       else if (rightchild == 0)
       {
           run_process("Right", l);
       fork_level (++l, c);   
       }
    }
    for (i=0; i<c; i++){
    wait (NULL);
     }
      fprintf(stderr, "Exiting: Level %d with pid= %ld, child of ppid= %ld\n",l,        (long)getpid(), (long)getppid());
 }
}

main(int argc, char *argv[])
{
   int i, N=0, M=0, I=0, pflag=0, uflag =0; 
   char Nchar [3], Mchar [3], ichar [3];
 for (i = 1; i < argc; i++) {
   if (strcmp (argv[i], "-u")==0  ){
      uflag=1;

   }
   else if (strcmp (argv[i], "-N")==0){
       i++;
       strcpy (Nchar, argv[i]);
       N= atoi (Nchar);

   }
   else if (strcmp (argv[i], "-M")==0){
       i++;
       strcpy (Nchar, argv[i]);
       level= atoi (Nchar);

   }
   else if (strcmp (argv[i], "-p")==0){
       pflag=1;
   }
   else if (strcmp (argv[i], "-s")==0){
       i++;
       strcpy (ichar, argv[i]);
       I= atoi (ichar);

   }

 }
   if (uflag==1){
       printf ("u.....\n");
   }
  fork_level (0, N);

}

以下是我运行代码./main -u -N 2 -M 2的方法 这是样本输出:

    ALIVE: Level 0 process with pid= 26534 child of ppid=26533
ALIVE: Level 0 process with pid= 26535 child of ppid=26533
ALIVE: Level 1 process with pid= 26536 child of ppid=26534
ALIVE: Level 1 process with pid= 26538 child of ppid=26534
ALIVE: Level 1 process with pid= 26537 child of ppid=26535
Exiting: Level 2 with pid= 26536, child of ppid= 26534
Exiting: Level 2 with pid= 26538, child of ppid= 26534
Exiting: Level 2 with pid= 26537, child of ppid= 26535
ALIVE: Level 1 process with pid= 26539 child of ppid=26535
Exiting: Level 2 with pid= 26539, child of ppid= 26535
Exiting: Level 1 with pid= 26534, child of ppid= 26533
Exiting: Level 1 with pid= 26535, child of ppid= 26533
Exiting: Level 1 with pid= 26535, child of ppid= 26533
ALIVE: Level 1 process with pid= 26540 child of ppid=26534
Exiting: Level 2 with pid= 26540, child of ppid= 26534
Exiting: Level 1 with pid= 26534, child of ppid= 26533
Exiting: Level 0 with pid= 26533, child of ppid= 25113

0 个答案:

没有答案