zoukankan      html  css  js  c++  java
  • Linux2.6 内核中结构体初始化(转载)

    转自:http://hnniyan123.blog.chinaunix.net/uid-29917301-id-4989879.html

       在Linux2.6版本的内核中,我们经常可以看到下面的结构体的定义和初始化。这在以前的C语言书中是极少见到的。下面的一个结构体来自到Linux内核中的一部分。在这个结构体中我们可以看到有普通的整型变量,也有函数的指针。

    struct net_proto_family {
        int        family;
        int        (*create)(struct net *net, struct socket *sock,
                     int protocol, int kern);
        struct module    *owner;
    };

      而在内核中可以使用下面的方法进行初始化。

    static const struct net_proto_family netlink_family_ops = {
        .family = PF_NETLINK,
        .create = netlink_create,
        .owner    = THIS_MODULE,    /* for consistency 8) */
    };

    下面是使用上面的结构体的一个小程序,其中还有结构体中的另外一种应用:

    #include <stdio.h>
    #define PF_ID 10
    
    enum
    {
        ID1 = 10,
        ID2,
        ID3,
    };
    
    char *message = "message";
    int create(int fd,char *name)
    {
        if(fd == 10)
          {
            printf ("I am create fd = %d,name = %s
    ",fd,name);
         }
        return 1;
    }
    
    int output (int fd,char *name)
    {
         printf("I am output fd =%d,name = %s
    ",fd,name);
         return 1;
    }
    
    int output_2 (int fd,char *name)
    {
        printf("I am output_2 fd = %d,name = %s
    ",fd,name);
    }
    
    struct test_1
    {
        int (*output)(int fd,char *name);
    };
    
    struct test
    {
        int id;
        char name[50];
        int (*print)(int fd,char *name);
    };
    
    static struct test des ={
    
        .id= PF_ID,
        .name ="frank",
        .print = create,
    };
    
    struct test_1 table[] = {
         [ID1] = {.output = output},
            [ID2] = {.output = output_2},
    };
    
    
    int main()
    {
        printf("des.PF_ID=%d
    ",des.id);
        printf("des.message= %s
    ",des.name);
        des.print(PF_ID,message);
        table[ID2].output(PF_ID,"table ID2");
        table[ID1].output(PF_ID,"table ID1");
    }

    这里有一篇分析Linux内核这种数据结构比较详细的文章。
    http://blog.csdn.net/mociml/archive/2009/08/13/4443280.aspx

  • 相关阅读:
    python之连接oracle数据库
    从一副牌中随机抽一张牌
    判断一个点是否在圆内
    判断每个月有多少天
    猜数字游戏
    求一元二次方程的2个跟
    Servlet细节处理
    Servlet
    Http协议
    Struts2(2)
  • 原文地址:https://www.cnblogs.com/lance-ehf/p/4648747.html
Copyright © 2011-2022 走看看