我自己在linux 6.0编译内核,,如下如我的内核源码:
文件名:kernel.c
代码:
#include <linux/module.h>#include <net/sock.h>#include <linux/netlink.h>#include <linux/skbuff.h>#define NETLINK_USER 31struct sock *nl_sk = NULL;static void hello_nl_recv_msg(struct sk_buff *skb){ struct nlmsghdr *nlh; int pid; struct sk_buff *skb_out; int msg_size; char *msg = "Hello from kernel"; int res; printk(KERN_INFO "Entering: %s\n", __FUNCTION__); msg_size = strlen(msg); nlh = (struct nlmsghdr *)skb->data; printk(KERN_INFO "Netlink received msg payload: %s\n", (char *)nlmsg_data(nlh)); pid = nlh->nlmsg_pid; /*pid of sending process */ skb_out = nlmsg_new(msg_size, 0); if (!skb_out) { printk(KERN_ERR "Failed to allocate new skb\n"); return; } nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0); NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */ strncpy(nlmsg_data(nlh), msg, msg_size); res = nlmsg_unicast(nl_sk, skb_out, pid); if (res < 0) printk(KERN_INFO "Error while sending bak to user\n");}static int __init hello_init(void){ printk("Entering: %s\n", __FUNCTION__); nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg, NULL, THIS_MODULE); if (!nl_sk) { printk(KERN_ALERT "Error creating socket.\n"); return -10; } return 0;}static void __exit hello_exit(void){ printk(KERN_INFO "exiting hello module\n"); netlink_kernel_release(nl_sk);}module_init(hello_init); module_exit(hello_exit);MODULE_LICENSE("GPL");
文件名:Makefile
代码:
obj-m = kernel.oKVERSION = $(shell uname -r)all: make -C /lib/modules/$(KVERSION)/build M=$(PWD) modulesclean: make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
当我一次执行命令:
1.make
2.insmod kernle.ko
然后内核报错:
insmod: error inserting ‘kernel.ko’: -1 Inavalid parameters
出错原因:
解决办法:
将kernel.c的文件名换成hello.c,同时将Makefile中对应的名称也换成hello,然后重新make,insmod问题解决~~
关于这个问题我还想补充几点:
1.Makefile文件中注意命令执行的部分,前面一定用tab键开头,否则编译的时候会出错。
2.这个编译程序是适用于linux平台下的,ubuntu平台下可能会报异常,大家一定注意!!!
3.关于这个问题,我还看到过csdn上另一个博客,如果我的方法无法解决,大家可以参考这篇博客:
最后,good luck~~
什么天荒地老,什么至死不渝。都只是锦上添花的借口…