detect usb hotplug


#include <stdio.h>
    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>  
    #include <ctype.h>  
    #include <sys/un.h>  
    #include <sys/ioctl.h>  
    #include <sys/socket.h>  
    #include <linux/types.h>  
    #include <linux/netlink.h>  
    #include <errno.h>  
    #include <unistd.h>  
    #include <arpa/inet.h>  
    #include <netinet/in.h>  
      
    #define UEVENT_BUFFER_SIZE 2048  
      
    static int init_hotplug_sock()  
    {  
        const int i_buffersize = 1024;  
        int i_ret = 0;  
      
        struct sockaddr_nl saddr_nl;  
        bzero( &saddr_nl, sizeof( struct sockaddr_nl ) );  
        saddr_nl.nl_family = AF_NETLINK;  
        saddr_nl.nl_pid = getpid();  
        saddr_nl.nl_groups = 1;  
      
        int i_sock = socket( PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT );  
        if ( -1 == i_sock )  
        {  
            perror( "socket" );  
            return -1;  
        }  
        setsockopt( i_sock, SOL_SOCKET, SO_RCVBUF, &i_buffersize, sizeof( i_buffersize ) );  
      
        i_ret = bind( i_sock, ( struct sockaddr * )&saddr_nl, sizeof( struct sockaddr_nl ) );  
        if (i_ret < 0)  
        {  
            perror("bind");  
            close(i_sock);  
            return -1;  
        }  
      
        return i_sock;  
    }  
      
    int main(int argc, char* argv[])  
    {  
        int i_rcvlen = 0;  
        int i_hotplug_sock = init_hotplug_sock();  
        if ( i_hotplug_sock < 0 )  
            return -1;  
      
        while(1)  
        {  
            /* Netlink message buffer */  
            char psz_buf[UEVENT_BUFFER_SIZE * 2] = {0};  
            i_rcvlen = recv(i_hotplug_sock, &psz_buf, sizeof(psz_buf), 0);  
            if ( i_rcvlen > 0 )  
            {  
                printf( "recv msg: %s, length: %d\n", psz_buf, strlen( psz_buf ) );  
      
                /* USB 设备的插拔会出现字符信息,通过比较不同的信息确定特定设备的插拔,在这添加比较代码 */  
            }  
        }  
        return 0;  
      
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值