0
votes

I'm trying to create 4 children processes from a parent and have each child execute something different.

int main(void) {
int processes = 4;
int i;
for (i = 1; i <= processes; i++) {
    if (fork() == 0) {
        printf("pid: %d\n", getpid());
        exit(0);
    }
}
int status;
for (i = 1; i <= processes; i++)
    wait(&status);
}

Right now the output produces pid: 5847 pid: 5846 pid: 5845 pid: 5844

Why are the pid's in decreasing rather than increasing orders? Am I not correctly using the fork() to create the children?

1
the pids can be in any order - why do you think otherwise?Ed Heal

1 Answers

0
votes

This is an optical illusion. The PIDs are in increasing order ;) Let me explain:

  • First, process 5844 is created
  • Then process 5845 is created
  • Then process 5846 is created
  • Then process 5847 is created
  • Then process 5847 is selected by the OS scheduler and prints "5847"
  • Then process 5846 is selected by the OS scheduler and prints "5846"
  • Then process 5845 is selected by the OS scheduler and prints "5845"
  • Then process 5844 is selected by the OS scheduler and prints "5844"

You just have no control over which process is selected first by the scheduler. But, if you add a sleep(1); to the end of your for loop, I'm sure the PIDs will be in increasing order (unless you hit the ceiling and they wrap around.)

At least Linux and OS X produces PIDs in increasing order, don't know about other Unix-like operating systems.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    int processes = 4;
    int i;
    int fork_result;
    int number_of_children;
    for (i = 1; i <= processes; i++) {
        fork_result = fork();
        if (fork_result > 0) {
            printf("parent says: hello child #%d, how are you?\n", fork_result);
            number_of_children++;
        } else if (fork_result == 0) {
            printf("pid: %d\n", getpid());
            exit(0);
        } else if (fork_result < 0) {
            printf("parent says: fork() failed\n");
        }
    }
    int status;
    for (i = 1; i <= number_of_children; i++) {
        wait(&status);
    }
}

On my system (OS X 10.10.5) this prints:

parent says: hello child #2577, how are you?
parent says: hello child #2578, how are you?
pid: 2577
pid: 2578
parent says: hello child #2579, how are you?
parent says: hello child #2580, how are you?
pid: 2579
pid: 2580

What OS are you using? The "parent says:" lines should be in increasing order in any case.