如何获取子进城结束时的返回值
时间: 2023-06-30 15:04:23 浏览: 43
获取子进程结束时的返回值可以使用 `wait` 系列函数,例如 `waitpid`。这些函数会阻塞当前进程直到子进程结束,并返回子进程的退出状态,即返回值。下面是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
exit(123);
} else if (pid > 0) {
// 父进程
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("子进程返回值为 %d\n", WEXITSTATUS(status));
}
} else {
// fork 出错
perror("fork");
return 1;
}
return 0;
}
```
在上面的代码中,父进程调用 `waitpid` 等待子进程结束,并将子进程的返回值保存在 `status` 变量中。然后使用 `WIFEXITED` 宏判断子进程是否正常结束,如果是,则使用 `WEXITSTATUS` 宏获取子进程的返回值。输出结果为:
```
子进程返回值为 123
```