Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of wait((int *)0)

Tags:

c

fork

pipe

One such program that uses a wait function like this is this one:

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{ 
    int pid,fd[2]; int n; char line[20];        
    if(pipe(fd)<0) { 
        printf("Error creating pipe"); 
    } else { 
        pid=fork(); 
        if(pid<0) { 
            printf("Error while forking"); 
        } else { 
            if(pid>0) { 
                close(fd[0]); 
                write(fd[1],"Hello\n",6); 
                while(wait((int *)0)!=pid);
            } else { 
                close(fd[1]); 
                n=read(fd[0],line,20); 
                if(n<0) 
                printf("Error reading a file"); 
                write(1,line,n); 
            } 
        } 
    } 
    return 0; 
}   
like image 571
skinderneath Avatar asked Mar 27 '09 14:03

skinderneath


2 Answers

See man wait(2).

wait((int *)0) calls waitpid(-1, (int *)0, 0). The man page states:

If status is not NULL, wait() and waitpid() store status information in the int to which it points.

Here, status is NULL (0). Thus, your call to wait waits for a state change in any child process, and does not return a status. The call merely checks to see if a state change occurred for a specific child process (pid in your case).

like image 185
strager Avatar answered Sep 23 '22 08:09

strager


stager's answer is correct. Though it should be noted that the cast is entirely unnecessary since according to the standard, 0 used in a pointer context is the NULL pointer.

like image 29
user83255 Avatar answered Sep 21 '22 08:09

user83255