您的位置:首页 > 运维架构 > Linux

Linux2.6 内核中结构体初始化(转载)

2015-07-15 16:30 543 查看
转自: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\n",fd,name);
}
return 1;
}

int output (int fd,char *name)
{
printf("I am output fd =%d,name = %s\n",fd,name);
return 1;
}

int output_2 (int fd,char *name)
{
printf("I am output_2 fd = %d,name = %s\n",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\n",des.id);
printf("des.message= %s\n",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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: