请使用netlink获取usb设备插拔事件,并提取出设备类型,名字,pid vid 文件路径等信息,请用C语言写出程序
时间: 2024-02-27 08:53:18 浏览: 91
好的,以下是一个简单的C程序,使用netlink获取usb设备插拔事件,并提取设备类型,名字,pid vid 文件路径等信息:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/usb/ch9.h>
#define UEVENT_BUFFER_SIZE 2048
int main()
{
struct sockaddr_nl nls;
struct msghdr msg;
struct iovec iov;
char buffer[UEVENT_BUFFER_SIZE];
int ret, fd, len;
struct nlmsghdr *nh;
struct udev_device *dev;
char *action, *subsystem, *devtype, *devname, *pid, *vid, *path;
memset(&nls, 0, sizeof(nls));
nls.nl_family = AF_NETLINK;
nls.nl_pid = getpid();
nls.nl_groups = -1;
if ((fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
if (bind(fd, (struct sockaddr *)&nls, sizeof(nls)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
memset(&msg, 0, sizeof(struct msghdr));
iov.iov_base = buffer;
iov.iov_len = sizeof(buffer);
msg.msg_name = (void *)&nls;
msg.msg_namelen = sizeof(nls);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
while (1) {
len = recvmsg(fd, &msg, 0);
if (len == -1) {
perror("recvmsg");
exit(EXIT_FAILURE);
}
nh = (struct nlmsghdr *)buffer;
while (NLMSG_OK(nh, len)) {
if (nh->nlmsg_type == NLMSG_DONE)
break;
else if (nh->nlmsg_type == NLMSG_ERROR) {
perror("NLMSG_ERROR");
exit(EXIT_FAILURE);
}
else if (nh->nlmsg_type == UDEV_MONITOR) {
action = strstr(NLMSG_DATA(nh), "ACTION=");
if (action != NULL) {
subsystem = strstr(NLMSG_DATA(nh), "SUBSYSTEM=");
devtype = strstr(NLMSG_DATA(nh), "DEVTYPE=");
devname = strstr(NLMSG_DATA(nh), "DEVNAME=");
pid = strstr(NLMSG_DATA(nh), "ID_VENDOR_ID=");
vid = strstr(NLMSG_DATA(nh), "ID_PRODUCT_ID=");
path = strstr(NLMSG_DATA(nh), "DEVPATH=");
if (action != NULL && subsystem != NULL && devtype != NULL &&
devname != NULL && pid != NULL && vid != NULL && path != NULL) {
printf("Action: %s\n", action + strlen("ACTION="));
printf("Subsystem: %s\n", subsystem + strlen("SUBSYSTEM="));
printf("Devtype: %s\n", devtype + strlen("DEVTYPE="));
printf("Devname: %s\n", devname + strlen("DEVNAME="));
printf("Pid: %s\n", pid + strlen("ID_VENDOR_ID="));
printf("Vid: %s\n", vid + strlen("ID_PRODUCT_ID="));
printf("Path: %s\n", path + strlen("DEVPATH="));
printf("\n");
}
}
}
nh = NLMSG_NEXT(nh, len);
}
}
close(fd);
return 0;
}
```
这个程序使用了netlink套接字来接收内核发送的消息,然后解析消息中的信息,提取出usb设备的相关信息,包括设备类型,名字,pid vid 文件路径等信息。
阅读全文