kernel4.4.194,请使用netlink获取usb设备插拔事件,并提取出设备类型,名字,pid vid 文件路径等信息,请用C语言写出程序
时间: 2024-02-27 11:54:17 浏览: 221
好的,下面是一个简单的C程序,可以使用netlink监听USB设备的插拔事件,并提取出设备类型,名称,PID,VID和文件路径等信息。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/usb/ch9.h>
#define UEVENT_BUFFER_SIZE 2048
int main(void)
{
int sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
if(sock_fd < 0)
{
perror("socket");
exit(EXIT_FAILURE);
}
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
addr.nl_groups = -1;
if(bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(EXIT_FAILURE);
}
char buf[UEVENT_BUFFER_SIZE];
while(1)
{
int len = recv(sock_fd, buf, sizeof(buf), 0);
if(len < 0)
{
perror("recv");
exit(EXIT_FAILURE);
}
struct nlmsghdr *nlh = (struct nlmsghdr *)buf;
while(NLMSG_OK(nlh, len))
{
if(nlh->nlmsg_type == NLMSG_DONE)
{
break;
}
if(nlh->nlmsg_type == NLMSG_ERROR)
{
perror("NLMSG_ERROR");
exit(EXIT_FAILURE);
}
struct udev_device *dev = udev_device_new_from_syspath(udev, (char *)NLMSG_DATA(nlh));
if(dev)
{
const char *devtype = udev_device_get_property_value(dev, "DEVTYPE");
const char *devname = udev_device_get_property_value(dev, "DEVNAME");
const char *devpath = udev_device_get_devpath(dev);
const char *idVendor = udev_device_get_sysattr_value(dev, "idVendor");
const char *idProduct = udev_device_get_sysattr_value(dev, "idProduct");
if(devtype && devname && devpath && idVendor && idProduct)
{
printf("Device Type: %s\n", devtype);
printf("Device Name: %s\n", devname);
printf("Device Path: %s\n", devpath);
printf("Vendor ID: %s\n", idVendor);
printf("Product ID: %s\n", idProduct);
printf("\n");
}
udev_device_unref(dev);
}
nlh = NLMSG_NEXT(nlh, len);
}
}
close(sock_fd);
return 0;
}
```
这个程序使用了libudev库来解析USB设备的信息。在每次接收到netlink消息时,程序会调用`udev_device_new_from_syspath()`函数来创建一个udev设备对象,然后使用`udev_device_get_property_value()`和`udev_device_get_sysattr_value()`函数来提取设备类型,名称,路径,PID和VID等信息。注意,需要先安装udev库才能编译运行这个程序。
阅读全文