Linux system Environment How to obtain the USB disk plug information _unix Linux

Source: Internet
Author: User
Tags socket
The following example listens to the kernel's HotPlug event, the source code is as follows:
Copy Code code as follows:

#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>

#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 (&AMP;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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.