使用inotify获取usb设备插拔事件,请用C语言写出程序
时间: 2024-02-27 20:55:25 浏览: 186
以下是使用inotify获取USB设备插拔事件的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/inotify.h>
#define EVENT_SIZE (sizeof (struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
int main(int argc, char **argv)
{
int fd, wd;
char buf[BUF_LEN];
int len, i = 0;
char *p;
struct inotify_event *event;
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return -1;
}
wd = inotify_add_watch(fd, "/dev/", IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
return -1;
}
while (1) {
len = read(fd, buf, BUF_LEN);
if (len < 0) {
perror("read");
return -1;
}
i = 0;
while (i < len) {
event = (struct inotify_event *) &buf[i];
if (event->mask & IN_CREATE) {
if (event->mask & IN_ISDIR) {
printf("The directory %s was created.\n", event->name);
} else {
printf("The file %s was created.\n", event->name);
}
} else if (event->mask & IN_DELETE) {
if (event->mask & IN_ISDIR) {
printf("The directory %s was deleted.\n", event->name);
} else {
printf("The file %s was deleted.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
```
该程序使用inotify机制监听/dev/目录下的IN_CREATE和IN_DELETE事件,当有USB设备插入或拔出时,会打印相应的消息。注意,该程序需要使用root权限运行。
阅读全文