fork

forkさせると、プログラムの流れがどうなるのかいまいちわからん。

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

int main()
{
    pid_t pid[10];
    int count = 0;

    for (; count < 10; count++) {
        pid[count] = fork();
        if (pid[count] < 0) {
            fprintf(stderr, "fork(2) failed.\n");
            exit(1);
        }

        if (pid[count] == 0) {
            sleep(1);
            printf("child process is running. (count=%d)\n", count);
            exit(0);
        }
    }

    for (count = 0; count < 10; count++) {
        int status;
        pid_t c_pid;
        c_pid = wait(&status);
        printf("parent process\n");
        printf("  child (PID=%d) finished.\n", c_pid);
    }

    return 0;
}
child process is running. (count=1)
child process is running. (count=2)
child process is running. (count=3)
parent process
  child (PID=5120) finished.
parent process
  child (PID=5119) finished.
child process is running. (count=0)
child process is running. (count=6)
child process is running. (count=4)
child process is running. (count=7)
child process is running. (count=5)
parent process
  child (PID=5125) finished.
parent process
  child (PID=5124) finished.
parent process
  child (PID=5122) finished.
parent process
  child (PID=5121) finished.
parent process
  child (PID=5118) finished.
child process is running. (count=8)
child process is running. (count=9)
parent process
  child (PID=5127) finished.
parent process
  child (PID=5126) finished.
parent process
  child (PID=5123) finished.