waitpid () from /lib64/libc.so.6
时间: 2024-09-15 18:01:49 浏览: 158
`waitpid()` 是 UNIX 和类 UNIX 系统中的一个系统调用,用于父进程获取其子进程的状态信息。这个函数定义在 `<sys/wait.h>` 头文件中。当子进程结束时,父进程可以调用 `waitpid()` 来获取子进程的退出状态,同时这个调用还可以控制父进程是否等待子进程结束。
函数原型如下:
```c
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *stat_loc, int options);
```
其中各参数的含义如下:
- `pid`: 指定要等待的子进程的进程 ID。如果设置为 `-1`,则等待任意子进程。
- `stat_loc`: 指向一个整型的指针,用于存储子进程的退出状态。如果不需要退出状态,此参数可以设置为 NULL。
- `options`: 控制 `waitpid()` 的行为,可以是 `WNOHANG`(非阻塞模式)、`WUNTRACED`(等待子进程停止状态)、`WCONTINUED`(等待继续后的子进程状态)等的组合。
`waitpid()` 返回值:
- 如果调用成功,返回子进程的 PID。
- 如果发生错误,则返回 `-1`,并将错误信息存储在全局变量 `errno` 中。
`waitpid()` 与 `wait()` 的区别主要在于 `waitpid()` 提供了更多的控制选项,包括可以选择非阻塞方式等待子进程结束,以及可以指定等待特定的子进程。
相关问题
编写process.c(路径为/home/mc/oslab/hdc/usr/root/,记得现输入./sudo mount-hdc挂载,具体文件见后文)
编写`process.c`文件通常是在Linux环境下的系统编程任务,这个文件可能会包含处理某个特定进程、线程或者其他操作系统相关的操作。假设您需要创建一个程序来监控或控制某个名为"hdctest"的进程,您可以按照以下步骤:
1. 打开终端并导航到指定目录:
```sh
cd /home/mc/oslab/hdc/usr/root
```
2. 如果`mount-hdc`命令是用来挂载外部设备的,确保已经挂载成功。如果没有,先运行该命令(如果它是一个脚本或二进制文件):
```sh
./sudo mount-hdc
```
注意:这里使用`sudo`是因为通常需要管理员权限来挂载设备。
3. 现在打开文本编辑器(如vim, nano或gedit),创建一个新的`process.c`文件:
```sh
vim process.c
```
或者如果您更喜欢使用其他编辑器,替换为相应的命令。
4. 编写过程管理函数,例如使用`fork()`和`execve()`来执行、控制或监控进程。示例代码可能如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// 定义要执行的进程路径和名称
const char* target_process = "/path/to/hdctest";
int main(int argc, char *argv[]) {
pid_t child_pid;
// 创建子进程
if ((child_pid = fork()) == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // 子进程
// 使用execlpe替换当前进程
if (execlpe(target_process, target_process, NULL) == -1) {
perror("Failed to execute process");
_exit(EXIT_FAILURE);
}
} else { // 父进程
// 等待子进程结束,并获取退出状态
int status;
waitpid(child_pid, &status, 0);
printf("Child process %d exited with status %d\n", child_pid, WEXITSTATUS(status));
}
return 0;
}
```
5. 保存并关闭文件后,编译它:
```sh
gcc -o process process.c
```
6. 最后,通过`./process`运行您编写的`process.c`程序。
20181445-2.1.c: In function ‘main’: 20181445-2.1.c:90:29: warning: passing argument 2 of ‘waitpid’ from incompatible pointer type [-Wincompatible-pointer-types] 90 | waitpid(pid,&stat,0); | ^~~~~ | | | int (*)(const char * restrict, struct stat * restrict) In file included from 20181445-2.1.c:7: /usr/include/x86_64-linux-gnu/sys/wait.h:111:45: note: expected ‘int *’ but argument is of type ‘int (*)(const char * restrict, struct stat * restrict)’ 111 | extern __pid_t waitpid (__pid_t __pid, int *__stat_loc, int __options);
这个编译警告是因为waitpid函数的第二个参数应该是一个指向int类型的指针,但是你传递的参数类型是一个指向函数的指针,因此参数类型不兼容。你需要修改代码,将第二个参数&stat改为指向int类型的指针变量,例如:
```
int status;
waitpid(pid, &status, 0);
```
这个修改会将status变量的地址传递给waitpid函数,使得waitpid函数能够在子进程退出时将子进程的状态信息存储到该变量中。这样就能解决编译警告的问题。
阅读全文
相关推荐















