Article Title: how to obtain the USB flash drive information in Linux. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
The traditional method for getting the information from the insert or unplug USB flash drive is to run the hotplug program at the kernel level. The relevant parameters are passed through the environment variables, and then hotplug notifies other applications concerned with hotplug. This method is somewhat less efficient. Now we use a special type of socket netlink to obtain the USB flash drive information. Netlink is used for asynchronous communication between kernel space and user space.
The following example monitors the hotplug event of the kernel. The source code is as follows:
# Include # Include # Include # Include # Include # Include # Include # Include # Include # Include # Define UEVENT_BUFFER_SIZE 2048 Static int init_hotplug_sock (void ); Int main (int argc, char * argv []) { Int hotplug_sock = init_hotplug_sock (); While (1 ){ Char buf [UEVENT_BUFFER_SIZE * 2] = {0 }; Recv (hotplug_sock, & buf, sizeof (buf), 0 ); Printf ("% s \ n", buf ); } Return 0; } 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_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; } |