Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wrote the following program and executed in terminal. But I am confused that the program isn't displaying the results as wait behavior is described on internet. I copied this code from a book.

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

int main(int argc, char *argv[])
pid_t childid;

    printf("Please an argument at terminal\n");
    return 0;

int i,n = atoi(argv[1]);


printf("i= %d\n Process ID %d\n Parent ID %d\n Child ID %d\n",i,getpid(),getppid(),childid);

return 0;


Should't the parent process execute the last "printf" statment n time, where n is the number of children created.. What happens when the parent calls while(wait(NULL)>0); and the child is still in excution?


share|improve this question
up vote 3 down vote accepted

The wait() system call suspends execution of the calling process until one of its children terminates.

wait() returns the pid of the child whose state is changed(or say terminated). It returns -1 in error ( when there is no child to wait for ).

So the while loop will be executed 0 times in child (forked) process. And in parent process it will be executed n (no of child process) times.

This program will print the last mesage n+1 times. ( 1 in the main, and n in the children)

share|improve this answer
I know that. My question is lets say this program creates 2 children, When first children terminates, shouldn't the parent process execute the last printf and prints its parent id.. Same goes for when the second process terminates. In the above program, the parent is executing the last statment only once. – Umer Farooq Sep 23 '12 at 12:19
parent is a single process, the last statement is only one, how it can execute more than once? – Deepak Sep 23 '12 at 12:21
ok. What is returned by wait(NULL) when the child process is still in execution? – Umer Farooq Sep 23 '12 at 12:23
it just blocks( or say sleeps ) the calling process when there is childrens are runnning, if any of them is terminated then it returns terminated process's id, if there is no process left(running) then it returns -1 ( and while loop terminates) – Deepak Sep 23 '12 at 15:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.