wait 和 waitpid 的 int* 类型的参数用两个字节记录
wait 的 status参数
* 高8位 记录进程调用exit退出的状态(正常退出)
* 低8位 记录进程接受到的信号 (非正常退出)
如果正常退出(exit) ---高8位是退出状态号,低8位是0
如果非正常退出(signal)----高八位是0,低8位是siganl id
例如
/*
* wait.c
*
* Created on: 2011-11-17
* Author: snape
*/
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
/*
* wait 的 status参数
* 高8位 记录进程调用exit退出的状态(正常退出)
* 低8位 记录进程接受到的信号 (非正常退出)
*/
int main(int argc, char **argv) {
pid_t id;
int status;
if ((id = fork()) < 0) {
perror("fork");
exit(1);
} else if (id == 0) {
fprintf(stderr, "child [%d] start!\n", getpid());
sleep(30);
fprintf(stderr, "child [%d] ends\n", getpid());
exit(6);
} else {
fprintf(stderr, "parent [%d] start to wait child [%d]!\n", getpid(), id);
waitpid(-1, &status, 0);
//如果是exit
fprintf(stderr, "child [%d] exit status is %d\n", id, status >> 8);
// 如果是 signal
fprintf(stderr, "child [%d] signal status is %d\n", id, status);
exit(0);
}
return 0;
}
处理status参数相关的宏
选自《UNIX环境高级编程》
WIFEXITED(status) 如果正常退出(exit)返回非零值;这时可以用WEXITSTATUS(status) 得到退出编号(exit的参数)
WIFSIGNALED(status) 如果异常退出 (子进程接受到退出信号) 返回非零值;使用WTERMSIG (status) 得到使子进程退出得信号编号
WIFSTOPPED(status) 如果是暂停进程返回的状态,返回非零值;使用WSTOPSIG(status) 得到使子进程暂停得信号编号
代码:
/*
* wait.c
*
* Created on: 2011-11-17
* Author: snape
*/
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
/*
* wait 的 status参数
* 高8位 记录进程调用exit退出的状态(正常退出)
* 低8位 记录进程接受到的信号 (非正常退出)
*/
int main(int argc, char **argv) {
pid_t id;
int status;
if ((id = fork()) < 0) {
perror("fork");
exit(1);
} else if (id == 0) {
fprintf(stderr, "child [%d] start!\n", getpid());
sleep(30);
fprintf(stderr, "child [%d] ends\n", getpid());
exit(6);
} else {
fprintf(stderr, "parent [%d] start to wait child [%d]!\n", getpid(), id);
waitpid(-1, &status, 0);
if (WIFEXITED(status)) {
fprintf(stderr, "child[%d] exit with code [%d]\n", id,
WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
fprintf(stderr, "child [%d] receive signal [%d] to exit\n", id,
WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
fprintf(stderr,"child [%d] stop with signal [%d]",id,WSTOPSIG(status));
}
// //如果是exit
// fprintf(stderr, "child [%d] exit status is %d\n", id, status >> 8);
// // 如果是 signal
// fprintf(stderr, "child [%d] signal status is %d\n", id, status);
exit(0);
}
return 0;
}
terminal 1;
(kill -9 3894)
snape@snape-virtual-machine:~/桌面$ gcc -o wait wait2.c
snape@snape-virtual-machine:~/桌面$ ./wait
parent [3893] start to wait child [3894]!
child [3894] start!
child [3894] receive signal [9] to exit
( 自动退出)
snape@snape-virtual-machine:~/桌面$ ./wait
parent [3965] start to wait child [3966]!
child [3966] start!
child [3966] ends
child[3966] exit with code [6]