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