Skip to content

Commit

Permalink
hotplug-netlink: sample program from kernel docs
Browse files Browse the repository at this point in the history
  • Loading branch information
karlp committed Feb 19, 2016
1 parent 523c7c3 commit e86d9c5
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 0 deletions.
34 changes: 34 additions & 0 deletions utils/hotplug-netlink/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#
# Copyright (C) 2016 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#

include $(TOPDIR)/rules.mk

PKG_NAME:=hotplug-netlink
PKG_RELEASE:=1
PKG_MAINTAINER:=Karl Palsson <karlp@etactica.com>

PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME)

include $(INCLUDE_DIR)/package.mk

define Package/$(PKG_NAME)
SECTION:=utils
CATEGORY:=Utilities
TITLE:=hotplug netlink debugger
DEPENDS:=+libc
endef

define Build/Prepare
$(CP) ./files/* $(PKG_BUILD_DIR)/
endef

define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/dbg-hotplug-netlink $(1)/usr/bin
endef

$(eval $(call BuildPackage,$(PKG_NAME)))
6 changes: 6 additions & 0 deletions utils/hotplug-netlink/files/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
APP=dbg-hotplug-netlink

all: $(APP)

clean:
$(RM) $(APP)
60 changes: 60 additions & 0 deletions utils/hotplug-netlink/files/dbg-hotplug-netlink.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* From https://www.kernel.org/doc/pending/hotplug.txt
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <linux/types.h>
#include <linux/netlink.h>

void die(char *s)
{
write(2, s, strlen(s));
exit(1);
}

int main(int argc, char *argv[])
{
struct sockaddr_nl nls;
struct pollfd pfd;
char buf[512];

// Open hotplug event netlink socket

memset(&nls, 0, sizeof(struct sockaddr_nl));
nls.nl_family = AF_NETLINK;
nls.nl_pid = getpid();
nls.nl_groups = -1;

pfd.events = POLLIN;
pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
if (pfd.fd == -1)
die("Not root\n");

// Listen to netlink socket

if (bind(pfd.fd, (void *) &nls, sizeof(struct sockaddr_nl)))
die("Bind failed\n");
while (-1 != poll(&pfd, 1, -1)) {
int i, len = recv(pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
if (len == -1) die("recv\n");

// Print the data to stdout.
i = 0;
while (i < len) {
printf("%s\n", buf + i);
i += strlen(buf + i) + 1;
}
}
die("poll\n");

// Dear gcc: shut up.
return 0;
}

0 comments on commit e86d9c5

Please sign in to comment.