检查wait和waitpid所返回的终止状态的宏
宏 说明 WIFEXITED(status) 若为正常终止子进程返回的状态,则为真。对于这种情况可执行WEXITSTATUS(status)。取子进程传送给exit,_exit或_Exit参数的低8位 WIFSIGNALED(status) 若为异常终止子进程返回的状态,则为真(接到一个不捕捉的信号),对于这种情况,可执行WTERMSIG(status),取使子进程终止的信号编号。另外,有些实现(非Single UNIX Specification)定义宏WCOREDUMP(status),若已产生终止进程的core文件,则它返回真。 WIFSTOPPED(status) 若为当前暂停子进程的返回的状态,则为真。对于这种情况,可执行WSTOPSIG(status),取使子进程暂停的信号编号 WIFCONTINUED(status) 若在作业控制暂停后已经继续的子进程返回了状态,则为真。(POSIX.1的XSI扩展,仅用于waitpid)。
wait和waitpid函数
#include < sys/ types. h>
#include < sys/ wait. h>
pid_t wait ( int * status) ;
status: 是一个整型数指针
非空: 子进程退出状态放在它所指向的地址中。
空: 不关心退出状态
返回值: 如果执行成功则返回子进程ID , 如果有错误发生则返回- 1 。
若正常终止子进程返回的状态, 为真, 我们可以执行WEXITSTATUS ( 上表介绍) 来获取所返回的值
调用 wait 函数时, 调用进程将会出现下面的情况:
- 如果其所有子进程都还在运行, 则阻塞。
- 如果一个子进程已经终止, 正等待父进程获取其终止状态, 则获取该子进程的终止状态然后立即返回。
- 如果没有任何子进程, 则立即出错返回。
pid_t waitpid ( pid_t pid, int * status, int options) ;
pid:
pid == - 1 等待任一子进程。就这一方面而言, waitpid与wait等效。
pid > 0 等待其进程ID 与pid相等的子进程。
pid == 0 等待其组ID 等于调用进程组ID 的任一子进程。
pid < - 1 等待其组ID 等于pid绝对值的任一子进程。
status: 是一个整型数指针
非空: 子进程退出状态放在它所指向的地址中。
空: 不关心退出状态
options: 一般为WNOHANG ( 下表介绍)
waitpid的option常量
常量 说明 WCONTINUED 若实现支持作业控制,那么由pid指定的任一子进程在暂停后已经继续。但其状态尚未报告,则返回其状态(POSIX.1的XSI扩展) WNOHANG 若由pid指定的子进程并不是立即可用的,则waitpid不阻塞,此时其返回值为0 WUNTRACED 若某实现支持作业控制,而由pid指定的任一子进程已处于暂停状态,并且其状态自暂停以来还未报告过,则返回其状态,WISTOPPED宏确定返回值是否对应于一个暂停子进程
#include < stdio. h>
#include < sys/ types. h>
#include < unistd. h>
#include < stdlib. h>
int main ( )
{
int cnt= 0 ;
int status= 1 ;
pid_t pid;
pid = fork ( ) ;
while ( 1 ) {
wait ( & status) ;
printf ( "child quit,child status=%d\n" , WEXITSTATUS ( status) ) ;
if ( pid > 0 ) {
printf ( "cnt=%d\n" , cnt) ;
printf ( "this is father course pid=%d\n" , getpid ( ) ) ;
sleep ( 1 ) ;
}
else if ( pid == 0 ) {
cnt++ ;
printf ( "this is child course pid=%d\n" , getpid ( ) ) ;
sleep ( 1 ) ;
if ( cnt == 5 ) {
exit ( 2 ) ;
}
}
}
return 0 ;
}
#include < stdio. h>
#include < sys/ types. h>
#include < unistd. h>
#include < stdlib. h>
int main ( )
{
int cnt= 0 ;
int status= 1 ;
pid_t pid;
pid = fork ( ) ;
while ( 1 ) {
waitpid ( pid, & status, WNOHANG ) ;
printf ( "child quit,child status=%d\n" , WEXITSTATUS ( status) ) ;
if ( pid > 0 ) {
printf ( "cnt=%d\n" , cnt) ;
printf ( "this is father course pid=%d\n" , getpid ( ) ) ;
sleep ( 1 ) ;
}
else if ( pid == 0 ) {
cnt++ ;
printf ( "this is child course pid=%d\n" , getpid ( ) ) ;
sleep ( 1 ) ;
if ( cnt == 5 ) {
exit ( 2 ) ;
}
}
}
return 0 ;
}