Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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;

if(argc!=2)
{
    printf("Please an argument at terminal\n");
    return 0;
}

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

for(i=0;i<n;i++)
{
    childid=fork();
    if(childid==0)
    {
        //sleep(20);
        break;
    }
}
while(wait(NULL)>0);

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?

Thanks

share|improve this question

1 Answer 1

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

 
discard

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.