The traditional way to get the insert or pull of u disk is to run the HotPlug program at the kernel level, the related parameters are passed through the environment variable, and then the HotPlug notice other application that concerns hotplug. This approach is somewhat inefficient, and is now implemented by a special type of socket NetLink to obtain the information of the USB disk pull plug. NetLink is dedicated to asynchronous communication between kernel space and user space.
Because NetLink is a built-in Linux feature, it's easy to use: Create a special file descriptor (Af_netlink) for the Netlink_kobject_uevent type under the protocol family Cpplive, It then uses setsocketopt to allow the file descriptor (socket) to reuse other ports, and then uses the band function to bind its process to a special file descriptor (a nested word) cpplive, and finally to listen for cpplive readable in the while loop using SELECT. If readable, call recv to receive data from the Linux kernel and print it out, which is USB hot-swappable information. Of course, you can also personalize the hot pluggable information from the kernel to make the program smarter and more humane.
Establish Net_link sockets, and real-time detection of the U state with kernel communication (basically consistent with basic socket programming)
#include
Include #include #include #include #include #include #include #include #include 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 = 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 * *
&buffersize, sizeof (buffersize));
retval = Bind (Hotplug_sock,
sizeof (struct sockaddr_nl));
if (retval < 0) {
printf ("Bind failed:%s", Strerror (errno));
Close (hotplug_sock);
Hotplug_sock =-1;
return-1;
}
return hotplug_sock;
}