netlink in linux

Keywords: socket Linux SDK

netlink in linux uses:

This code snippet appears in the file: app video ueventmonitor ueventmonitor. c, and is a thread created at the time of sdk initialization.

Preliminary analysis of the role of this code is to use netlink mechanism to receive, event interruption message, parse the received message, according to different message content, perform different operations. It mainly involves the following events:

1. Battery state events. For example, the electricity is too low.

2. Block device events. For example: the insertion of sd card.

3.usb events. For example: macrousb insertion,

4. The temperature state update event of the chip.

5. The addition of camera, etc.

static void *event_monitor_thread(void *arg)
{
    int sockfd;
    int i, j, len;
    char buf[512];
    struct iovec iov;
    struct msghdr msg;
    struct sockaddr_nl sa;
    struct _uevent event;

    prctl(PR_SET_NAME, "event_monitor", 0, 0, 0);

    pthread_mutex_init(&collision_lock, NULL);

    memset(&sa, 0, sizeof(sa));
    sa.nl_family = AF_NETLINK;
    sa.nl_groups = NETLINK_KOBJECT_UEVENT;
    sa.nl_pid = 0;
    memset(&msg, 0, sizeof(msg));
    iov.iov_base = (void *)buf;
    iov.iov_len = sizeof(buf);
    msg.msg_name = (void *)&sa;
    msg.msg_namelen = sizeof(sa);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    sockfd = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
    if (sockfd == -1) {
        printf("socket creating failed:%s\n", strerror(errno));
        goto err_event_monitor;
    }

    if (bind(sockfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
        printf("bind error:%s\n", strerror(errno));
        goto err_event_monitor;
    }

    if (parameter_get_video_usb() == 0)
        android_usb_config_ums();
    else if (parameter_get_video_usb() == 1)
        android_usb_config_adb();
 //   else if (parameter_get_video_usb() == 3)
 //      android_usb_config_rndis();

    battery_init();
    cvr_sd_ctl(1);

    while (1) {
        event.size = 0;
        len = recvmsg(sockfd, &msg, 0);
        if (len < 0) {
            printf("receive error\n");
        } else if (len < 32 || len > sizeof(buf)) {
            printf("invalid message");
        } else {
            for (i = 0, j = 0; i < len; i++) {
                if (*(buf + i) == '\0' && (i + 1) != len) {
                    event.strs[j++] = buf + i + 1;
                    event.size = j;
                }
            }
        }
        parse_event(&event);
    }

err_event_monitor:
    pthread_detach(pthread_self());
    pthread_exit(NULL);
}

 

Posted by coelex on Wed, 31 Jul 2019 07:45:24 -0700