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.