问题描述:

I am trying to create 2 children and then they get and argument which tells how many children those 2 have to create like so:

I get 2 arguments for example 2 and 3 and they have to create that many. I did it with for and it kinda works but parent dies before his second child dies

[email protected]:~/4laboras$ ./testas 2 3

pid=389 ppid=387

pid=390 ppid=387

pid=386 ppid=27959

pid=391 ppid=388

[email protected]:~/4laboras$ pid=387 ppid=1

pid=392 ppid=388

pid=388 ppid=1

pid=393 ppid=388

My code:

#include <stdio.h>

#include <unistd.h>

#include <sys/wait.h>

#include <stdlib.h>

int main( int argc, char *argv[] ){

pid_t child1;

pid_t child2;

int i, a, b;

child1 = fork();

if (child1 != 0){

child2=fork();

}

if (child1 == 0){

for (i=1; i<=atoi(argv[1]); i++){

if (a !=0){

a=fork();

if (a == 0){

printf("pid=%d ppid=%d\n", getpid(),getppid());

exit(1);

}

}

}

}

else

if (child2 == 0){

for (i=1; i<=atoi(argv[2]); i++){

if(b !=0){

b=fork();

if (b == 0){

printf("pid=%d ppid=%d\n", getpid(),getppid());

exit(1);

}

}

}

}

printf("pid=%d ppid=%d\n", getpid(),getppid());

return 0;

}

网友答案:

Use wait or waitpid to wait in parent until all children finish execution.

Be careful not to create a fork bomb.

网友答案:
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int main( int argc, char *argv[] ){
    pid_t child1;
    pid_t child2;
    int status;
    int i, a, b;
    child1 = fork();
    if (child1 != 0){
        child2=fork();
    }
    if (child1 != 0 & child2 != 0){
        wait(&status);
    }
    if (child1 == 0){
    for (i=1; i<=atoi(argv[1]); i++){
        if (a !=0){
            a=fork();
            if (a == 0){
                printf("pid=%d ppid=%d\n", getpid(),getppid());
                exit(1);
            }
        }
        }
    }
    else if (child2 == 0){
        printf("pid=%d ppid=%d\n", getpid(),getppid());
        for (i=1; i<=atoi(argv[2]); i++){
            if(b !=0){
                b=fork();
                if (b == 0){
                    exit(1);
                }
            }
        }
    exit(status);
    }
    printf("pid=%d ppid=%d\n", getpid(),getppid());
    return 0;
}
相关阅读:
Top