在osx系統中有一個奇怪的現象,就是在子程序退出的時候waitpid會被中斷一次,errno傳回EINTR号,如果給SIGCHLD改成自己的實作就不會出現這種情況,不知道osx的darwin核心對SIGCHLD的預設處理做了什麼。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <termios.h>
#include <errno.h>
int chld = 0;
void sig_chld(int signo) {
chld = 1;
}
int main(){
pid_t pid ,errnopid = 0;
int status = 0;
//signal(SIGCHLD, sig_chld);
if( 0 > ( pid = fork())){
printf("fork error\n");
}else if( 0 == pid) {
printf("child\n");
sleep(10);
exit(123);
}
while ((errnopid = waitpid(pid, &status, 0)) != pid) {
if( EINTR == errno)
printf("EINTR = %d , status = %d , chld %d\n",errnopid,status,chld);
}
printf("pid = %d , status %d ,errnopid %d \n",pid,status,errnopid);
return 0;
}
child
EINTR = -1 , status = 0 , chld 0
pid = 5854 , status 31488 ,errnopid 5854
child
EINTR = -1 , status = 0 , chld 0
pid = 5854 , status 31488 ,errnopid 5854
Output:childEINTR = -1 , status = 0 , chld 0pid = 5854 , status 31488 ,errnopid 5854
這裡使用while的話可以處理這種情況的。