O2 - 使用libudev获取设备信息(VirtualBox USB设备管理)

这篇博客介绍了如何通过libudev库来获取和管理VirtualBox的USB设备信息,参考了相关文档和示例代码。
摘要由CSDN通过智能技术生成

/** udev_get.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>  
#include <string.h>
#include <pthread.h>
#include <sys/stat.h>  
#include <sys/epoll.h>
#include <sys/utsname.h>
#include <libudev.h>
#include "udev_get.h"

#define DEVDEBUG

static struct user_devices *listhead = NULL;
static struct user_devices *listtail = NULL;
static struct user_devices *listread = NULL;
static pthread_mutex_t listmutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t atomicmutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t g_pthid;
static int monitor_stop = 0;
static int initmark = 0;

enum devtype {DEVNULL = 0, DEVCHAR = 1, DEVBLK, DEVALL};
static int find_devtype(const char *devpath)
{
	struct stat devstat;
	if (NULL == devpath)
		return DEVNULL;
	if (stat(devpath, &devstat))
		return DEVNULL;

	//printf("%s (%d)\n", devpath, (int)devstat.st_mode);
	/*	必须先检查是否为块文件,根据定义来看,块设备都是字符设备
		#define	__S_IFCHR	0020000	Character device.	0010 0000 0000 0000
		#define	__S_IFBLK	0060000	Block device.		0110 0000 0000 0000
	*/
	if (S_IFBLK == (devstat.st_mode & S_IFBLK))
		return DEVBLK;
	else if(S_IFCHR == (devstat.st_mode & S_IFCHR))
		return DEVCHAR;
	else
		return DEVALL;
}

static int device_equal(struct user_devices *dev1, struct user_devices *dev2)
{
	if (NULL == dev1 || NULL == dev2) return 0;
	if (!strcmp(dev1->serial, dev2->serial)) 
		return 1;

	if (dev1->vendor_id[0] && dev2->vendor_id[0] && dev1->model_id[0] && dev2->model_id[0])
		if(!strcmp(dev1->vendor_id, dev2->vendor_id) && !strcmp(dev1->model_id, dev2->model_id))
			return 1;

	return 0;
	
}

static struct user_devices *list_find_dev_serial(struct user_devices *aimdev)
{
	pthread_mutex_lock(&listmutex);

	struct user_devices *retval = NULL;
	if (NULL == listhead || NULL == aimdev) goto out;
	struct user_devices *pdev = listhead;
	while(NULL != pdev) {
		if (device_equal(pdev, aimdev)) {
			retval = pdev;
			goto out;
		} else
			pdev = pdev->next;
	}

out:
	pthread_mutex_unlock(&listmutex);
	return retval;
}

static void insert_devnum(struct user_devices *in, struct user_devices *val)
{
	int i;
	for(i = 0; i < in->subdev_cnt; i++) {
		if (in->sdev[i].major == val->sdev[0].major && in->sdev[i].minor == val->sdev[0].minor)
			break;
	}
	if (i == in->subdev_cnt) {
		snprintf(in->sdev[i].syspath, sizeof(in->sdev[0].syspath), "%s", val->sdev[0].syspath);
		snprintf(in->sdev[i].devname, sizeof(in->sdev[0].devname), "%s", val->sdev[0].devname);
		in->sdev[i].major = val->sdev[0].major
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值