waitpid(等待子進程中斷或結束)
表頭文件
#include<sys/types.h>
#include<sys/wait.h>
定義函數 pid_t waitpid(pid_t pid,int * status,int options);
函數說明
waitpid()會暫時停止目前進程的執行,直到有信號來到或子進程
結束。如果在調用 wait()時子進程已經結束,則 wait()會立即
返回子進程結束狀態值。 子進程的結束狀態值會由參數 status 返回,
而子進程的進程識別碼也會一起返回。如果不在意結束狀態值,則
參數 status 可以設成 NULL。參數 pid 為欲等待的子進程識別碼,
其他數值意義如下:
pid<-1 等待進程組識別碼為 pid 絕對值的任何子進程。
pid=-1 等待任何子進程,相當于 wait()。
pid=0 等待進程組識別碼與目前進程相同的任何子進程。
pid>0 等待任何子進程識別碼為 pid 的子進程。
參數 option 可以為 0 或下面的 OR 組合:
WNOHANG 如果沒有任何已經結束的子進程則馬上返回, 不予以等待。
WUNTRACED 如果子進程進入暫停執行情況則馬上返回,但結束狀態不予以理會。
子進程的結束狀態返回后存于 status,底下有幾個宏可判別結束情況:
WIFEXITED(status)如果子進程正常結束則為非 0 值。
WEXITSTATUS(status)取得子進程 exit()返回的結束代碼,一般會先用 WIFEXITED 來判斷是否正常結束才能使用此宏。
WIFSIGNALED(status)如果子進程是因為信號而結束則此宏值為真
WTERMSIG(status) 取得子進程因信號而中止的信號代碼,一般會先用 WIFSIGNALED 來判斷后才使用此宏。
WIFSTOPPED(status) 如果子進程處于暫停執行情況則此宏值為真。一般只有使用 WUNTRACED 時才會有此情況。
WSTOPSIG(status) 取得引發子進程暫停的信號代碼,一般會先用 WIFSTOPPED 來判斷后才使用此宏。
如果執行成功則返回子進程識別碼(PID) ,如果有錯誤發生則返回
返回值-1。失敗原因存于 errno 中。
/******
* waitpid.c - Simple wait usage
*********/
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
pid_t childpid;
int status;
childpid = fork();
if ( -1 == childpid )
{
perror( "fork()" );
exit( EXIT_FAILURE );
}
else if ( 0 == childpid )
{
puts( "In child process" );
sleep( 3 );//讓子進程睡眠3秒,看看父進程的行為
printf("\tchild pid = %d\n", getpid());
printf("\tchild ppid = %d\n", getppid());
exit(EXIT_SUCCESS);
}
else
{
waitpid( childpid, &status, 0 );
puts( "in parent" );
printf( "\tparent pid = %d\n", getpid() );
printf( "\tparent ppid = %d\n", getppid() );
printf( "\tchild process exited with status %d \n", status );
}
exit(EXIT_SUCCESS);
}
[root@localhost src]# gcc waitpid.c
[root@localhost src]# ./a.out
In child process
child pid = 4469
child ppid = 4468
in parent
parent pid = 4468
parent ppid = 4379
child process exited with status 0
[root@localhost src]#
如果將上面“waitpid( childpid, &status, 0 );”行注釋掉,程序執行效果如下:
[root@localhost src]# ./a.out
In child process
in parent
parent pid = 4481
parent ppid = 4379
child process exited with status 1331234400
[root@localhost src]# child pid = 4482
child ppid = 1
子進程還沒有退出,父進程已經退出了。