- /* file : genl_kernel.c
- * kernel module for test genetlink
- * sudochen@163.com
- *
- */
- #include <linux/init.h>
- #include <linux/module.h>
- #include <net/genetlink.h>
- static int cmd_echo(struct sk_buff *skb_2, struct genl_info *info);
- enum {
- CMD_NONE,
- CMD_ECHO,
- CMD_MAX
- };
- static struct genl_family cmd_genl_family = {
- .id = GENL_ID_GENERATE,
- .hdrsize = 0,
- .name = "cmd",
- .version = 1,
- .maxattr = CMD_MAX,
- };
-
- static struct nla_policy cmd_nla_policy[CMD_MAX + 1] = {
- [CMD_NONE] = {
- .type = NLA_UNSPEC,
- },
- [CMD_ECHO] = {
- .type = NLA_STRING,
- .len = 0x100,
- },
- };
- static struct genl_ops cmd_ops[] = {
- {
- .cmd = CMD_ECHO,
- .flags = 0,
- .policy = cmd_nla_policy,
- .doit = cmd_echo,
- .dumpit = NULL,
- }
- };
- static int cmd_echo(struct sk_buff *skb_2, struct genl_info *info)
- {
- struct nlattr *attr = NULL;
- struct sk_buff *skb = NULL;
- int ret = -1;
- char *data;
- char *head;
- if (NULL == info) {
- return -1;
- }
-
- attr = info->attrs[CMD_ECHO];
- if (attr) {
- data = (char*)nla_data(attr);
- if (data) {
- printk("genl recv data %s\n",data);
- } else {
- printk("genl recv data NULL\n");
- }
- } else {
- printk("no attr %d\n",CMD_ECHO);
- }
-
- skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
- if (NULL == skb) {
- goto out;
- }
- head = genlmsg_put(skb, 0, info->snd_seq+1,&cmd_genl_family,0,CMD_ECHO);
- if (NULL == head) {
- goto out;
- }
- ret = nla_put_string(skb, CMD_ECHO, "hello world form kernel space");
- if (ret)
- goto out;
- genlmsg_end(skb,head);
- ret = genlmsg_unicast(&init_net,skb,info->snd_pid);
- if (ret)
- goto out;
-
- return 0;
- out:
- printk("genl an error ocured\n");
- return -1;
- }
- int __init cmd_init(void)
- {
- int error;
- error = genl_register_family_with_ops(&cmd_genl_family, cmd_ops, ARRAY_SIZE(cmd_ops));
- if (error) {
- printk("register family error\n");
- return error;
- }
- printk("register family ok\n");
- return 0;
- }
- void __exit cmd_exit(void)
- {
- genl_unregister_family(&cmd_genl_family);
- printk("unregister family ok\n");
- }
-
- MODULE_LICENSE("GPL");
- module_init(cmd_init);
- module_exit(cmd_exit);
复制代码
|