/* !> Fork example [Ferd] */ #include #include #include #include #include int main(int argc, char **argv) { pid_t child; // Variable to store the child's process identifier printf("Creating 5 child processes\n"); for (int i = 0; i < 5; ++i) { child = fork(); if (child == 0) { // in the newly created child process printf("In child process %d\n", i); return i; // at this point, this child will exit with its number as exit code } else { printf("In the parent process. Just created child with PID %d\n", child); // parent continues working through the for loop } } // Now wait for 5 child processes to finish for (int i = 0; i < 5; ++i) { printf("Waiting for child to finish\n"); int status; pid_t finished_child = wait(&status); // wait for a child to finish printf("Child with PID %d finished with status %d\n", finished_child, WEXITSTATUS(status)); } return 0; }