这次浅聊一下两个头文件errno.h和
sys/wait.h 。
1. errno.h
定义:
errno.h 是一个用于错误处理的头文件,它定义了一个全局变量 errno,用于表示系统调用的错误码。
作用:
在调用系统函数或库函数时,如果出现错误,通常会设置 errno 的值来指示具体的错误原因。这样,程序可以通过检查 errno 的值来确定错误类型,并采取相应的错误处理措施。
其中定义的变量:
errno:一个全局整型变量,用于存储错误码。
具体用法:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
int main() {
int fd = open("nonexistent.txt", O_RDONLY);
if (fd == -1) {
perror("open"); // 使用 perror 函数根据 errno 打印错误信息
return 1;
}
// ... 其他代码 ...
close(fd);
return 0;
}
2. sys/wait.h
定义:
sys/wait.h 是一个用于进程等待和状态获取的头文件,它提供了一组函数和宏,用于父进程等待子进程的结束,并获取子进程的结束状态。
作用:
在创建子进程后,父进程通常需要使用这些函数来等待子进程的结束,并获取子进程的退出状态或接收到的信号。
其中定义的函数:
pid_t wait(int *status): 等待任意一个子进程结束,并返回其进程ID。
pid_t waitpid(pid_t pid, int *status, int options): 等待指定进程ID的子进程结束,或根据选项等待任意子进程。
其中定义的宏:
WIFEXITED(status): 检查子进程是否正常退出。
WEXITSTATUS(status): 获取子进程的退出状态。
WIFSIGNALED(status): 检查子进程是否因为接收到信号而终止。
WTERMSIG(status): 获取导致子进程终止的信号。
具体用法:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { // 子进程
printf("Child process (PID %d) is running...\n", getpid());
exit(42); // 子进程退出,并设置退出状态为 42
} else { // 父进程
int status;
pid_t child_pid = wait(&status); // 父进程等待子进程结束
if (WIFEXITED(status)) { // 检查子进程是否正常退出
printf("Child process (PID %d) exited with status %d\n", child_pid, WEXITSTATUS(status));
}
}
return 0;
}