- wait
- waitpid
wait函数用于等待子进程的退出:
#include#include pid_t wait ( int *status );
status用来保存子进程退出时的一些状态。如果不在意子进程的退出状态,可以设定status为NULL。
如果执行成功,wait会返回子进程的PID;如果没有子进程,则wait返回-1。
#include#include #include #include #include int main ( void ) { pid_t pc, pr; pc = fork(); if ( pc < 0 ) { printf ( "error ocurred!n" ); } else if ( pc == 0 ) { printf ( "This is child process with pid of %dn", getpid() ); sleep ( 10 ); } else { pr = wait ( NULL ); printf ( "I catched a child process with pid of %dn", pr ); } exit ( 0 ); }
执行结果:
This is child process with pid of 298 等待10秒 I catched a child process with pid of 298
如果参数status的值不是NULL,wait就会把子进程退出时的状态取出,并存入其中。
可以使用以下宏来处理status:
- WIFEXITED(status):用来指出子进程是否为正常退出,如果是,则会返回一个非零值。
- WEXITSTATUS(status):当WIFEXITED返回非零值时,可以用这个宏来提取子进程的返回值。
#include#include #include #include #include int main ( void ) { int status; pid_t pc, pr; pc = fork(); if ( pc < 0 ) { printf ( "error ocurred!n" ); } else if ( pc == 0 ) { printf ( "This is child process with pid of %dn", getpid() ); exit ( 3 ); } else { pr = wait ( &status ); if ( WIFEXITED ( status ) ) { printf ( "the child process %d exit normallyn", pr ); printf ( "the return code is %dn", WEXITSTATUS ( status ) ); } else { printf ( "the child process %d exit abnormallyn", pr ); } } }
编译并运行:
This is child process with pid of 308 the child process 308 exit normally the return code is 3waitpid
waitpid的函数原型如下:
#include#include pid_t waitpid ( pid_t pid, int *status, int options );
从本质上讲,waitpid和wait的作用是完全相同的,但waitpid多出了两个可以由用户控制的参数pid和options:
- pid:当pid取不同的值时,在这里有不同的意义:
| 取值 | 意义 |
|---|---|
| pid > 0 | 只等待进程ID等于pid的子进程 |
| pid = -1 | 等待任何一个子进程退出,此时waitpid和wait的作用一模一样 |
| pid = 0 | 等待同一个进程组中的任何子进程 |
| pid < -1 | 等待一个指定进程组中的任何子进程,这个进程组的ID等于pid的绝对值 |
- options:最常用的选项是WNOHANG,作用是即使没有子进程退出,它也会立即返回。
waitpid的返回值有如下几种情况:
- 当正常返回时,waitpid返回子进程的PID。
- 如果设置了WNOHANG,而waitpid没有发现已经退出的子进程,则返回0。
- 如果waitpid出错,则返回-1。例如参数pid指示的子进程不存在,或此进程存在,但不是调用进程的子进程。
#include#include #include #include #include int main ( void ) { pid_t pc, pr; pc = fork(); if ( pc < 0 ) { printf ( "Error occured on forkingn" ); } else if ( pc == 0 ) { sleep ( 3 ); exit ( 0 ); } do { pr = waitpid ( pc, NULL, WNOHANG ); if ( pr == 0 ) { printf ( "No child exitedn" ); sleep ( 1 ); } } while ( pr == 0 ); if ( pr == pc ) { printf ( "successfully get child %dn", pr ); } else { printf ( "some error occuredn" ); } }
执行结果:
No child exited No child exited No child exited successfully get child 340



