#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include <assert.h>
int main(void){
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
}
if (pid == 0) {
int i;
for (i = 3; i > 0; i--) {
printf("This is the child\n");
sleep(1);
}
//assert(1==2);
exit(10); // 子进程退出状态
}
else {
int stat_val; // 子进程的终止信息通过这个参数传出
waitpid(pid, &stat_val, 0); // 参数0,使得WNOHANG 可以使父进程不阻塞而立即返回0
if (WIFEXITED(stat_val)) // WIFEXITED 取出的字段值非零 -> 正常终止
printf("Child exited with code%d\n", WEXITSTATUS(stat_val));
// WEXITSTATUS 取出的字段值就是子进程的退出状态
else if (WIFSIGNALED(stat_val)) //WIFSIGNALED 取出的字段值非零-> 异常终止
printf("Child terminated abnormally, signal %d\n", WTERMSIG(stat_val));
// WTERMSIG 取出的字段值就是信号的编号
}
return 0;
}
结果:
This is the child
This is the child
This is the child
Child exited with code3
##################################################################
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include <assert.h>
int main(void){
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
}
if (pid == 0) {
int i;
for (i = 3; i > 0; i--) {
printf("This is the child\n");
sleep(1);
}
assert(1==2);
exit(10); // 子进程退出状态
}
else {
int stat_val; // 子进程的终止信息通过这个参数传出
waitpid(pid, &stat_val, 0); // 参数0,使得WNOHANG 可以使父进程不阻塞而立即返回0
if (WIFEXITED(stat_val)) // WIFEXITED 取出的字段值非零 -> 正常终止
printf("Child exited with code%d\n", WEXITSTATUS(stat_val));
// WEXITSTATUS 取出的字段值就是子进程的退出状态
else if (WIFSIGNALED(stat_val)) //WIFSIGNALED 取出的字段值非零-> 异常终止
printf("Child terminated abnormally, signal %d\n", WTERMSIG(stat_val));
// WTERMSIG 取出的字段值就是信号的编号
}
return 0;
}
结果:
This is the child
This is the child
This is the child
2: main4.c:21: main: Assertion `1==2' failed.
Child terminated abnormally, signal 6