gtpc2m9iC/C++ Language Support User's Guide

waitpid-Obtain Status Information from a Child Process

This function allows the calling process to obtain the exit status information from a child process.

Options permit the caller to either suspend execution of the calling process until a child process ends or return immediately.

Format

#include   <sys/wait.h>
pid_t waitpid(pid_t pid, int *stat_loc,
             int options);

pid
A set of child processes for which status is requested. Only one status is returned per waitpid function call.

stat_loc
A pointer to an integer where the wait function will return the status of the child process. If the waitpid function returns because a process has exited, the return value is equal to the pid of the exiting process. For this, if the value of stat_loc is not NULL, information is stored in the location pointed to by stat_loc. If status is returned from a terminated child process that returned a value of 0, the value stored at the location pointed to by stat_loc is 0. If the return is greater than 0, you can evaluate this information using the following macros:

WEXITSTATUS

WIFEXITED

WIFSIGNALED

WTERMSIG.

options
0 or the following flag:

WNOHANG
The waitpid function does not suspend the calling process if status is not immediately available for any process specified by the pid parameter.

Normal Return

The normal return is one of the following:

Error Return

If unsuccessful, the waitpid function returns a value of -1 and sets errno to one of the following:

ECHILD
The process specified by the pid parameter does not exist.

EINVAL
The value of the options argument is not valid.

Programming Considerations

Examples

The following example shows how the waitpid function is used to wait for a single child process to exit and query its exit status.

#include <sysapi.h>
#include <signal.h>
#include <sys/wait.h>

·
·
·
pid_t child_pid; pid_t rc_pid; int chld_state; int my_opt=WNOHANG;
·
·
·
/* Create a child process*/ child_pid = tpf_fork(&create_parameters);
·
·
·
/* Check status of child process*/ rc_pid = waitpid( child_pid, &chld_state, WNOHANG); if (rc_pid > 0) { if (WIFEXITED(chld_state)) { printf("Child exited with RC=%d\n",WEXITSTATUS(chld_state)); } if (WISIGNALED(chld_state)) { printf("Child exited via signal %d\n",WTERMSIG(chld_state)); } } else /* If no error, continue*/ { if (rc_pid < 0) { if (errno == ECHILD) { printf("Child does not exist\n"); } else { printf("Bad argument passed to waitpid\n"); abort(); } } }
·
·
·

Related Information