百度空间 | 百度首页 
 
查看文章
 
kernel和udev间传递消息
2008-05-29 10:40
kernel和udev间传递消息,比如add,remove等,是通过netlink进行。 netlink是个通用的机制,传递udev event只是其中一个应用。
由于uevent是广播的,所以写个小程序很容易不会这些事件。
写得比较匆忙,也很丑陋,呵呵。
#include <stdio.h>
#include <sys/socket.h>
#include <linux/netlink.h>

char buf[2048 + 512];
int main()
{
    int bufsize = 16 * 1024 * 1024;
    struct sockaddr_nl anl;
    int res, i, sk;

    anl.nl_family = AF_NETLINK;
    anl.nl_pid = getpid();
    anl.nl_groups = 1;

    sk = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if (sk == -1){
        printf("socket create failed\n");
        return sk;
    }
   
    setsockopt(sk, SOL_SOCKET, SO_RCVBUFFORCE, &bufsize, sizeof(bufsize));
    res = bind(sk, &anl, sizeof(anl));
    if (res == -1){
        close(sk);
        printf("socket bind failed\n");
        return res;
    }

    while(1){
    res = recv(sk, buf, sizeof(buf), 0);
    printf("res:%d\n",res);
    res = res > sizeof(buf) ? sizeof(buf) : res;
    printf("begin\n");
    for(i=0; i<res; i++)
        putchar(buf[i]);
    printf("end\n");
    }
    return 0;

}

类别:Linux | 添加到搜藏 | 浏览() | 评论 (1)
 
最近读者:
 
网友评论:
1
2008-07-05 10:26 | 回复
很牛x啊 早就想学一下udev了
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu