面试题答案
一键面试以下是关键代码片段:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
} else if (pid == 0) {
// 子进程
exit(3); // 这里以3作为退出状态示例,可以是其他值
} else {
// 父进程
wait(&status);
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
if (exit_status == 0) {
printf("子进程正常退出,退出状态为0\n");
} else {
printf("子进程异常退出,退出状态为 %d\n", exit_status);
}
}
}
return 0;
}
wait()
函数的作用:
wait(&status)
函数用于使父进程阻塞,直到它的一个子进程终止或者接收到一个不能被忽略的信号。- 当一个子进程终止时,
wait()
函数会解除父进程的阻塞状态,并通过status
参数返回子进程的退出状态。通过WIFEXITED(status)
宏可以判断子进程是否正常退出,如果是,再通过WEXITSTATUS(status)
宏获取子进程的退出状态值。这样父进程就可以根据子进程的退出状态进行相应的处理。