如何使父进程等待子进程完成?

问题描述 投票:0回答:1

我有一个分配,可以让我将此代码转换为使父进程等待所有子进程完成的代码。PS:第一个代码有4个过程,需要使用waitpid来解决。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
  pid_t p = fork();
  pid_t k = fork();

  if(p>0){
     printf("p=%d: PID = %d\n", p, getpid());
     sleep(45);
     exit(0);
  }
  else if(p==0){
     printf("p=%d: PID = %d\n", p, getpid());
     exit(0);
  }
  else if(p<0){
     printf("ERRO! p=%d\n", p);
     exit(p);
  }
}

我已经尝试过,但是我认为这仅适用于1个子进程,不适用于许多子进程。

int main(){

    pid_t p = fork(); 
    pid_t k = fork(); 

    if(p<0){
        printf("fodeu");
        exit(p);
    }
    else if(p==0){
        printf("");
        exit(0);
    }
    else{
        for(i=0;i<4;i++){
            int returnstatus; 
            waitpid(p,&returnstatus,0);

            if(returnstatus == 0){
                printf("o processo filho correu normalmente");
            }
            else if(returnstatus == 1){
                printf("o processo filho ardeu");
            }
        }
    }
}
c ubuntu fork pid waitpid
1个回答
0
投票

这是一种实现方法;会有很多其他人。

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

static void wait_for_kids(void);

int main(void)
{
    pid_t p = fork();
    pid_t k = fork();

    if (p > 0)
    {
        printf("p=%d: PID = %d\n", p, getpid());
        sleep(5);
        wait_for_kids();
        printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
        exit(0);
    }
    else if (p == 0)
    {
        printf("p=%d: PID = %d\n", p, getpid());
        wait_for_kids();
        printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
        exit(0);
    }
    else
    {
        printf("ERRO! p=%d\n", p);
        wait_for_kids();
        printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
        exit(p);
    }
    /*NOTREACHED*/
}

static void wait_for_kids(void)
{
    int corpse;
    int status;
    int pid = getpid();

    while ((corpse = waitpid(0, &status, 0)) > 0)
        printf("%d: child %d exited with status 0x%.4X\n", pid, corpse, status);
}

示例输出:

p=43445: PID = 43444
p=43445: PID = 43446
p=0: PID = 43445
p=0: PID = 43447
43447: p =     0, k =     0 - exiting
43445: child 43447 exited with status 0x0000
43445: p =     0, k = 43447 - exiting
43446: p = 43445, k =     0 - exiting
43444: child 43445 exited with status 0x0000
43444: child 43446 exited with status 0x0000
43444: p = 43445, k = 43446 - exiting
© www.soinside.com 2019 - 2024. All rights reserved.