Linux 接收热插拔事件

1、Linux 使用netlink接收热插拔事件代码:

static int init_hotplug_sock(void)
{
    struct sockaddr_nl snl;
    const int buffersize = 64 * 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_DGRAM, 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;
}

int main(int argc, char* argv[])
{
	int hotplug_sock       = init_hotplug_sock();
	fd_set rfds;
	struct timeval tv;
	int retval;
	char buf[128] = {0};
	char results[UEVENT_BUFFER_SIZE] = {0};
	char msg[512]={0};
	
	while(1){
		FD_ZERO(&rfds);
		FD_SET(hotplug_sock, &rfds);
		tv.tv_sec = 5;
		tv.tv_usec = 0;
		retval = select(hotplug_sock + 1, &rfds, NULL, NULL, &tv);

		if (retval == -1)
			perror("select() \n");
		else if (retval){
			memset(buf, 0, sizeof(buf));
			recv(hotplug_sock, buf, sizeof(buf), 0); 
			printf("%s\n", buf);
			//check_insert(buf);
		}
		else{

		}
	}
	return 0;
}



你可能感兴趣的:(Linux 接收热插拔事件)