本文主要是介绍Linux 应用层检测USB转串口设备热插拔事件程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用NETLINK检测USB热插拔的C语言实现代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <pthread.h>
#define UEVENT_BUFFER_SIZE 2048
static int init_hotplug_sock(void)
{
struct sockaddr_nl snl;
const int buffersize = 16 * 1024 * 1024;
int retval;
memset(&snl, 0x00, sizeof(struct sockaddr_nl));
snl.nl_family = AF_NETLINK;
snl.nl_pid = getpid();
snl.nl_groups = 1;
int hotplug_sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
if (hotplug_sock == -1) {
printf("error getting socket: %s", strerror(errno));
return -1;
}
/* set receive buffersize */
setsockopt(hotplug_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
retval = bind(hotplug_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
if (retval < 0) {
printf("bind failed: %s", strerror(errno));
close(hotplug_sock);
hotplug_sock = -1;
return -1;
}
return hotplug_sock;
}
unsigned char getHotPlugPort(char *buf)
{
unsigned char portNum = 0xff;
if (strstr(buf, "/usb5/5-1/5-1.5") != NULL)
{
portNum = 5;
}
else if (strstr(buf, "/usb5/5-1/5-1.4") != NULL)
{
portNum = 4;
}
else if (strstr(buf, "/usb5/5-1/5-1.3") != NULL)
{
portNum = 3;
}
else if (strstr(buf, "/usb5/5-1/5-1.2") != NULL)
{
portNum = 2;
}
else if (strstr(buf, "/usb5/5-1/5-1.1") != NULL)
{
portNum = 1;
}
else if (strstr(buf, "/usb5/3-1/3-1.1") != NULL)
{
portNum = 6;
}
return portNum;
}
void HotPlugThread(void)
{
struct timeval tv;
fd_set fds;
int rcvlen, ret,type=0,portNum=0;
int hotplug_sock = init_hotplug_sock();
printf("HotPlugthread start \n");
while (1)
{
//printf("sunqidong debug\n");
char buf[UEVENT_BUFFER_SIZE * 2] = { 0 };
FD_ZERO(&fds);
FD_SET(hotplug_sock, &fds);
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
ret = select(hotplug_sock + 1, &fds, NULL, NULL, &tv);
if (ret < 0)
continue;
if (!(ret > 0 && FD_ISSET(hotplug_sock, &fds)))
continue;
/* receive data */
rcvlen = recv(hotplug_sock, &buf, sizeof(buf), 0);
if (rcvlen > 0) {
if (strstr(buf, "add") != NULL)
{
portNum = getHotPlugPort((char*)&buf);
type = 1;
}else if (strstr(buf, "remove") != NULL)
{
portNum = getHotPlugPort((char*)&buf);
type = 0;
}
//printf("hotplug receive portNum = %d\n", portNum);
if ((portNum >= 1) && (portNum <= 6))
{
if (type == 0)
{
printf("hotplug remove portNum = %d\n", portNum);
}
else
{
printf("hotplug add portNum = %d\n", portNum);
}
}
/*You can do something here to make the program more perfect!!!*/
}
}
}
这篇关于Linux 应用层检测USB转串口设备热插拔事件程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!