C语言写一个posix接口测试U盘插拔的函数
时间: 2023-11-22 16:54:36 浏览: 31
下面是一个使用 POSIX 接口测试 U 盘插拔的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define USB_DEVICE_PATH "/dev/sda1" // U 盘设备路径
int main() {
int fd;
struct stat st;
int inserted = 0; // 标记 U 盘是否插入
while (1) {
// 获取 U 盘设备状态信息
if (stat(USB_DEVICE_PATH, &st) == -1) {
if (inserted) {
printf("U盘已拔出\n");
inserted = 0;
}
} else {
if (!inserted) {
printf("U盘已插入\n");
inserted = 1;
}
}
// 每 1 秒检测一次
sleep(1);
}
return 0;
}
```
该程序会不断地检测 U 盘设备文件 `/dev/sda1` 的状态,如果设备不存在,则认为 U 盘已经拔出;如果设备存在,则认为 U 盘已经插入。可以根据需要对程序进行修改和扩展。