4

I have this small program in c and I am trying to understand how it works, it is a simple while loop that uses fork() and wait() to print out a few lines on the command line, I have commented to the best of my ability what I think is happening

for (i = 1; i <= 3; i++)            /*simple while loop, loops 3 times */
{
    pid = fork();                   /*returns 0 if a child process is created */
    if(pid == 0){                   /*pid should be a 0 for first loop */
        printf("Hello!\n");         /*we print hello */
        return (i);                 /*will this return i to the parent process that called fork? */ 
    }   else {                      /*fork hasn't returned 0? */
        pid = wait(&j);             /*we wait until j is available? */
        printf("Received %d\n", WEXITSTATUS(j));   /*if available we print "received (j)" */
    }
}

This program is supposed to print:

Hello!
Received 1
Hello!
Received 2
Hello!
Received 3

When one of the child processes returns i does the parent process wait for it as &j? This is really confusing me, any help would be greatly appreciated.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
user3545370
  • 205
  • 1
  • 4
  • 16
  • 1
    `fork()` isn't `pthread_create()`, so `return`ing from the function that called `fork()` doesn't necessarily terminate the process. Post *all* of the relevant code. – EOF Aug 15 '15 at 10:53
  • 1
    See [`fork(2)`](http://linux.die.net/man/2/fork) and [`wait(2)`](http://linux.die.net/man/2/wait). Everything is explained there ... –  Aug 15 '15 at 10:55
  • the function: fork() has three possible return states '-1' when an error occurs, '0' if executing child and some positive number when executing parent. The posted code is not handling the error return. – user3629249 Aug 16 '15 at 06:46

1 Answers1

7

In each iteration of the loop fork() creates a child process. The child process prints Hello! and returns i to the system. The parent process blocks on wait() until child finishes execution. j will contain the value that the child process returned to the system.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
Hrant
  • 496
  • 1
  • 5
  • 13
  • That's great, really gives me a good way to visualize how the code is working, thanks :) – user3545370 Aug 15 '15 at 11:18
  • 2
    It should be noted that even though the child process returns an `int`, only the least significant byte is made available to the parent process waiting on the termination status. Furthermore, this value must be fetched with `WEXITSTATUS()` (as shown in the code), but it is only safe to do so when `WIFEXITED()` returns true (which the code fails to do). – Filipe Gonçalves Aug 15 '15 at 15:29