Child and Parent process with fork()

2019-09-20 13:23发布

问题:

I'm having problems, I need to make a program that make 9 child processes, after that I have to put a countdown of 3 seconds and make these 9 processes to wait for a signal from the father, after they receive this signal, every children should say what children he is (if he is the children #1, #2, #3, etc..., in order in which they were made).

What I've done is here, everything is OK, I think, until the part where I have to say as a children, what is my number, I don't have a clue how to do it, because each children is a different process, they don't share memory and the signal can't use arguments for that, by now I'm printing the PID on the function called "handler", but how can I print my number, as a Children?.

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

void handler(int x);

int main() {    
    pid_t child[9];
    pid_t child_pid;

    for (int i = 0; i < 9; ++i) {
        child_pid = fork();
        child[i] = child_pid;

        if (child_pid == 0)
            break;

        if (child_pid < 0) {
            perror("fork()");
            exit(EXIT_FAILURE);
        }
    }

    if (child_pid == 0) {
        signal(SIGUSR1, handler);
        pause();
    } else {
        printf("Countdown:\n");
        sleep(1);
        printf("3\n");
        sleep(1);
        printf("2\n");
        sleep(1);
        printf("1\n");
        sleep(1);

        for (int i = 0; i < 9; i++)
            kill(child[i], SIGUSR1); 

        waitpid(-1, NULL, 0);
    }

    return 0;
}

void handler(int sig) {
    printf("This is Child #%d\n", getpid());

    exit(0);
}

回答1:

Create a global variable:

int my_number;

Then in your loop that creates the children, do:

    if (child_pid == 0) {
        my_number = i;
        break;
    }

Then you can use the variable in the handler:

void handler(int sig) {
    printf("This is Child #%d\n", my_number);

    exit(0);
}