Process wait using linux system call wait

713 views Asked by At

I am trying to create a process using fork system call and then wait on the child process. I have used the following:

waitpid (pid, &status, 0);

1) The first problem is that the status is 8 bit shifted to the left e.g., if the child process returns 1, the waitpid function returns the value of the status in the status variable to be 256. Please let me know why it is doing that.

2) According to the manual, the waitpid waits for the child process to change state. but then it also says:

"The wait() system call suspends execution of the calling process until one of its children terminates. The call wait(&status) is equivalent to:

waitpid(-1, &status, 0);"

I am a bit confused here whether the waitpid and the wait calls wait for state change or for child process termination. Kindly clearify this point.

What does the zero in the third arguement specifies?

3) If i put the child process in sleep state, doesn't the state of the child process changes to be in waiting state by waiting for e.g., 5 secs?

Following is my program:

int main(int argc, char ** argv)   
{  
pid_t pid = fork();  
pid_t ppp;  

if (pid==0)
{
    sleep(8);
    printf ("\n I am the first child and my id is %d \n", getpid());
    printf ("The first child process is now exiting now exiting\n\n");
    exit (1);
}

else {
            int status = 13;
            printf ("\nI am now waiting for the child process %d\n", pid);
            waitpid (pid, &status, 0);
            printf ("\n the status returned by the exiting child is %d\n", status>>8);
        }

printf("\nI am now exiting");
exit(0);

}

Thanks

1

There are 1 answers

0
n. m. could be an AI On

The status parameter encodes more than just the exit code of the child. From man waitpid:

WIFEXITED(status)
returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.

main waitpid explains what the third parameter does.

The value of options is an OR of zero or more of the following constants:
WNOHANG
return immediately if no child has exited.
WUNTRACED
also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
WCONTINUED (since Linux 2.6.10)
also return if a stopped child has been resumed by delivery of SIGCONT.

State change is very precisely and narrowly defined. From man waitpid:

A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal.

Going to sleep is not a state change. Being stopped by SIGSTOP/SIGTSTP is.