|
wait()的函數(shù)原型是:
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status)
進程一旦調(diào)用了wait,就立即阻塞自己,由wait自動分析是否當前進程的某個子進程已經(jīng)退出。如果讓它找到了這樣一個已經(jīng)變成僵尸的子進程,wait就會收集這個子進程的信息,并把它徹底銷毀后返回;如果沒有找到這樣一個子進程,wait就會一直阻塞在這里,直到有一個出現(xiàn)為止。
參數(shù)status用來保存被收集進程退出時的一些狀態(tài),它是一個指向int類型的指針。但如果我們對這個子進程是如何死掉的毫不在意,只想把這個僵尸進程消滅掉,(事實上絕大多數(shù)情況下,我們都會這樣想),我們就可以設(shè)定這個參數(shù)為NULL,就象下面這樣:
pid = wait(NULL);
如果成功,wait會返回被收集的子進程的進程ID,如果調(diào)用進程沒有子進程,調(diào)用就會失敗,此時wait返回-1,同時errno被置為ECHILD。
WIFEXITED(status) 這個宏用來指出子進程是否為正常退出的,如果是,它會返回一個非零值。
WEXITSTATUS(status) 當WIFEXITED返回非零值時,我們可以用這個宏來提取子進程的返回值,如果子進程調(diào)用exit(5)退出,WEXITSTATUS(status)就會返回5;如果子進程調(diào)用exit(7),WEXITSTATUS(status)就會返回7。請注意,如果進程不是正常退出的,也就是說,WIFEXITED返回0,這個值就毫無意義。
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
void f(){
printf("THIS MESSAGE WAS SENT BY PARENT PROCESS..\n");
}
main(){
int i,childid,status=1,c=1;
signal(SIGUSR1,f); //setup the signal value
i=fork(); //better if it was: while((i=fork)==-1);
if (i){
printf("Parent: This is the PARENT ID == %d\n",getpid());
sleep(3);
printf("Parent: Sending signal..\n");
kill(i,SIGUSR1); //send the signal
//status is the return code of the child process
wait(&status);
printf("Parent is over..status == %d\n",status);
//WIFEXITED return non-zero if child exited normally
printf("Parent: WIFEXITED(status) == %d\n",WIFEXITED(status));
//WEXITSTATUS get the return code
printf("Parent: The return code WEXITSTATUS(status) == %d\n",WEXITSTATUS(status));
} else {
printf("Child: This is the CHILD ID == %d\n",getpid());
while(c<5){
sleep(1);
printf("CHLID TIMER: %d\n",c);
c++;
}
printf("Child is over..\n");
exit(2);
}
}
輸出:
Child: This is the CHILD ID == 8158
Parent: This is the PARENT ID == 8157
CHLID TIMER: 1
CHLID TIMER: 2
Parent: Sending signal..
THIS MESSAGE WAS SENT BY PARENT PROCESS..
CHLID TIMER: 3
CHLID TIMER: 4
Child is over..
Parent is over..status == 512
Parent: WIFEXITED(status) == 1 //正常退出
Parent: The return code WEXITSTATUS(status) == 2 //拿到子進程返回值
|
|
|