簡體   English   中英

C:等待兄弟進程終止

[英]C: Wait for brothers process termination

我的程序必須創建n個孩子。 收到信號后,將創建一個孩子。 然后第一個孩子等待其他n-1個孩子。 第二個等待其他n-2個孩子,依此類推,直到最后一個孩子跑完並立即完成。 我寫了這段代碼,但是沒有用,我有了侄子。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
void func(int sign)
{
    printf("received signal. I create a child\n");
}

int main(int argc, char*argv[])
{
    if(argc!=3)
    {
        printf("error\n");
        return 0;
    }
    int i,pid,status;
    int n=atoi(argv[1]);
    unsigned int m=(unsigned int)atoi(argv[2]);
    signal(SIGALRM,func);
    printf("i'm father: pid %d\n",getpid());
    for(i=0; i<n; i++)
    {
        alarm(m);
        pause();
        switch(pid=fork())
        {
        case -1:
            printf("error\n");
            break;
        case 0: 
            printf("i'm the hild numer %d, my pid is %d\n",i,getpid());
            if(i!=n-1)
            {
                wait(NULL);
                break;
            }
            else
            {
                printf("%d i have fnished\n",getpid());
                exit(0);
            }
            break;
        default:
            wait(NULL); 
            break;
        }
     }
     printf("finish\n");
     return 0;
}

代碼的結構方式是創建2^N進程。

您需要在以下位置更改代碼:

default:
   wait(NULL);
   break;

到那以后不再派生任何孩子的事情。 一種方法是使用goto語句。 這是更新版本。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

void func(int sign)
{
   printf("received signal. I create a child\n");
}

int main(int argc, char*argv[])
{
   if(argc!=3)
   {
      printf("error\n");
      return 0;
   }
   int i,pid,status;
   int n=atoi(argv[1]);
   unsigned int m=(unsigned int)atoi(argv[2]);
   signal(SIGALRM,func);
   printf("i'm father: pid %d\n",getpid());
   for(i=0; i<n; i++)
   {
      alarm(m);
      pause();
      switch(pid=fork())
      {
         case -1:
            printf("error\n");
            break;

         case 0:
            printf("i'm the child numer %d, my pid is %d\n",i,getpid());
            if(i!=n-1)
            {
               wait(NULL);
               break;
            }
            else
            {
               printf("%d i have fnished\n",getpid());
               exit(0);
            }
            break;

         default:
            wait(NULL);
            goto done;
      }
   }

done:
   printf("%d i have fnished\n",getpid());
   return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM