Netlink giving kernel panic

后端 未结 1 1758
难免孤独
难免孤独 2021-01-16 16:38

I tried this program. This program send \"hello\" to kernel and kernel replies \"hello\" to user space again for one time.

My requirement: user has to send \"hello\"

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 16:55

    Well, I thought the problem is in Kernel module. But the problem is in user module. I worked 3 days to identify this problem. The problem is at

    while(1) {           
        sleep(2);
        printf("Sending message to kernel\n");
        sendmsg(sock_fd,&msg,0);     // In 2nd iteration msg value chaged
    
        recvmsg(sock_fd, &msg, 0);  // <--- msg will update
        printf("Received message payload: %s\n", (char *)NLMSG_DATA(nlh));
    }
    

    This loops works only once. That is true. After receiving the message using recvmsg, msg variable is updated and I used that variable to send again. This is because of the code is over smart, both(source and destination) are referring to same pointer.

    By writing different variables for sendmsg and recvmsg will remove the problem.

    int main()
    {
        int seq_no = 1;
        sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);
        if(sock_fd<0)
                return -1;
    
        memset(&src_addr, 0, sizeof(src_addr));
        src_addr.nl_family = AF_NETLINK;
        src_addr.nl_pid = getpid(); /* self pid */
    
        bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
    
        memset(&dest_addr, 0, sizeof(dest_addr));
        dest_addr.nl_family = AF_NETLINK;
        dest_addr.nl_pid = 0; /* For Linux Kernel */
        dest_addr.nl_groups = 0; /* unicast */
    
        nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
        memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
        nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
        nlh->nlmsg_pid = getpid();
        nlh->nlmsg_flags = 0;
    
        strcpy(NLMSG_DATA(nlh), "Hello");
    
        iov.iov_base = (void *)nlh;
        iov.iov_len = nlh->nlmsg_len;
        msg.msg_name = (void *)&dest_addr;
        msg.msg_namelen = sizeof(dest_addr);
        msg.msg_iov = &iov;
        msg.msg_iovlen = 1;
                                                /* receiver parameters */
        nlh_in = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
        iov_in.iov_base = (void *)nlh_in;
        iov_in.iov_len = nlh->nlmsg_len;
        msg_in.msg_iov = &iov_in;
        msg_in.msg_iovlen = 1;                  /* end */
    
        while(1) {
            printf("sending message to kernel\n");
            sendmsg(sock_fd,&msg,0);
    
            recvmsg(sock_fd, &msg_in, 0);
            printf("Received message payload: %s\n", (char *)NLMSG_DATA(nlh_in));
            sleep(1);
        }
        free(nlh);
        close(sock_fd);
    }
    

    0 讨论(0)
提交回复
热议问题