Linux父進程等待子進程結束

wait()的函數原型是:
#include <sys/types.h>  
#include <sys/wait.h> 
pid_t wait(int *status)


進程一旦調用了wait,就立即阻塞自己,由wait自動分析是否當前進程的某個子進程已經退出。如果讓它找到了這樣一個已經變成殭屍的子進程,wait就會收集這個子進程的信息,並把它徹底銷燬後返回;如果沒有找到這樣一個子進程,wait就會一直阻塞在這裏,直到有一個出現爲止。


參數status用來保存被收集進程退出時的一些狀態,它是一個指向int類型的指針。但如果我們對這個子進程是如何死掉的毫不在意,只想把這個殭屍進程消滅掉,(事實上絕大多數情況下,我們都會這樣想),我們就可以設定這個參數爲NULL,就象下面這樣:
pid = wait(NULL); 


如果成功,wait會返回被收集的子進程的進程ID,如果調用進程沒有子進程,調用就會失敗,此時wait返回-1,同時errno被置爲ECHILD。


WIFEXITED(status) 這個宏用來指出子進程是否爲正常退出的,如果是,它會返回一個非零值。


WEXITSTATUS(status) 當WIFEXITED返回非零值時,我們可以用這個宏來提取子進程的返回值,如果子進程調用exit(5)退出,WEXITSTATUS(status)就會返回5;如果子進程調用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 //拿到子進程返回值
發佈了44 篇原創文章 · 獲贊 7 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章