1

I'm having problems with fork/waitpid functions.

I'm trying to make program what first processes and prints children PIDS and after that Parent PID

My code:

int main(void)
{
    pid_t pid;
    int rv = 0;
    int i = 1;
    pid_t child_pids[2];

    for (i = 0; i < 2; i++)
    {

        switch (pid = fork())
        {
        case -1:
            perror("fork");
            exit(1);

        case 0:
            pid = getpid();
            exit(i);
            break;

        default:
            child_pids[i] = pid;
            break;
        }
    }
    if (pid != 0 && pid != -1) {
        for (i = 0; i<2; i++){
            int status = 0;
            printf("PARENT: waiting for child %d (%d)\n", i, child_pids[i]);
            rv = waitpid(child_pids[i], &status, 0);
            printf("Child: %d, Here!!!\n", i);

        }
        printf("parent pid = %d\n", getpid());

    }
}

Currently it creates parent first and after that children.. So Someone have any tips what to do?

Tanhua
  • 39
  • 1
  • 5
  • What do you mean by "creates parent first"? The parent process is the process being run, it has to exist in order for the children to be created. Could you include your output? – Daniel Kleinstein Feb 11 '15 at 12:54

1 Answers1

2

From waitpid(2)'s manpage:

The value of pid can be: [...] -1 meaning wait for any child process.

and

waitpid(): on success, returns the process ID of the child whose state has changed; [...]

This means that you can simply loop on waitpid at the end of your main like so:

#define FORKED_CHILDREN 2

if (pid != 0 && pid != -1) {
    for (int collected = 0; collected < FORKED_CHILDREN; ++collected) {
        pid_t cpid = waitpid(-1, NULL, 0);
        printf("Child pid: %d\n", cpid);
    }
    printf("parent pid = %d\n", getpid());
}
Snaipe
  • 1,191
  • 13
  • 25