How to receive Kernel uevents with Netlink socket?
<p>I'm trying to receive uevent from the kernel via a netlink socket, when a USB device is (dis)connects. I have a python script that does the same job and it works, but I need the same functionality in C. So far I have this:</p>

<pre><code>#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;linux/netlink.h&gt;
#include &lt;unistd.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#define NL_MAX_PAYLOAD 8192

int main () {
    int nl_socket;
    struct sockaddr_nl src_addr, dest_addr;
    struct nlmsghdr* nlh;
    struct msghdr msg;
    struct iovec iov;

    // Prepare source address
    memset(&amp;src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid();

    // Prepare destination address
    memset(&amp;dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0;
    dest_addr.nl_groups = 0;

    // Prepare netlink message
    nlh = (struct nlmsghdr*) malloc(NLMSG_SPACE(NL_MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(NL_MAX_PAYLOAD));
    nlh-&gt;nlmsg_len = NLMSG_SPACE(NL_MAX_PAYLOAD);
    nlh-&gt;nlmsg_pid = getpid();
    nlh-&gt;nlmsg_flags = 0;
    iov.iov_base = (void *) nlh;
    iov.iov_len = nlh-&gt;nlmsg_len;
    msg.msg_iov = &amp;iov;
    msg.msg_iovlen = 1;

    nl_socket = socket(AF_NETLINK, SOCK_DGRAM,      NETLINK_KOBJECT_UEVENT);
    if (nl_socket &lt; 0) {
        printf("Failed to create socket for DeviceFinder");
        exit(1);
    }

    bind(nl_socket, (struct sockaddr*) &amp;src_addr, sizeof(src_addr));

    while (1) {
        int r = recvmsg(nl_socket, &amp;msg, 0);
        printf("%i\n", r);
        if (r &lt; 0) {
            perror("");
        }
    }
}
</code></pre>

<p>This is taken out of context to create a small, working example.</p>

<p>The problem is that I just don't receive anything. I don't get any errors,  the call of recvmsg just never returns when I (un)plug a device. Why?</p>