首页 > 技术相关 > Linux(ubuntu)下开发并添加内核模块

Linux(ubuntu)下开发并添加内核模块

2011年11月15日 发表评论 阅读评论

首先,大致有以下一些地方需要用到Linux内核编程:

  • 驱动开发,linux下的大部分驱动都是以内核模块的形式执行的。
  • 使用了一些特权指令的程序,比如wrmsr这些指令,这些指令需要在ring0下执行,一般这种程序也是以内核模块的形式执行。

下面简要介绍一下,一个Hello world的内核模块开发并且添加的过程(其实网上很多教程,但是发现都是针对比较老的内核,有些已经不适用了,因此,在此处,我在罗唆一下,也当是个备忘)。

  1. 首先需要安装开发库和头文件。
    $:sudo apt-get install linux-kernel-devel
    $:sudo apt-get install linux-headers-`uname -r`
  2. 写个hello_kernel.c(我保留了我代码中的获取cpuID的代码,所以严格不算helloword了),下面代码中printk是内核中的printf,打印的信息回打到内核log中,可以通过dmesg或者cat /var/log/kern.log查看。module_init以及module_exit分别为内核进入以及退出的函数。
    #include <linux/module.h>
    //#include <linux/config.h>//这个头文件在老的内核中有,新的内核已经没有了,因此注释调
    #include <linux/init.h>
    
    void bcopy(unsigned char *src,unsigned char *des,int count)
    {
    	int i=0;
    	for (i=0;i<count;i++)
    	{
    	  printk("src[%d]=%x\n",i,src[i]);
    	  des[i]=src[count-i];
    	}
    
    }
    
    void get_CPUID()
    {
        // 定义一些变量,用于存储 CPU 的 ID信息
    
        char szCpu[16]={0};
      unsigned int szCpu0,szCpu1,szCpu2;
        unsigned int uCpuID;
      int i = 0;
    
        __asm__ __volatile__(
          "push %%ebx;"
          "push %%ecx;"
          "push %%edx;"
          "mov $0, %%eax;"
          "cpuid;"
          "mov %%ebx, %0;"
          "mov %%edx, %1;"
          "mov %%ecx, %2;"
          "mov $1, %%eax;"
          "cpuid;"
          "mov %%edx, %3;"
          "pop %%ebx;"
          "pop %%ecx;"
          "pop %%edx;"
          :"=r"(szCpu0),"=r"(szCpu1),"=r"(szCpu2),"=r"(uCpuID)
          :
        );
      printk("szCpu0=%x,szCpu1=%x,szCpu2=%x\n",szCpu0, szCpu1, szCpu2);
      bcopy((unsigned char *)&szCpu0,(unsigned char *)szCpu,4);
      bcopy((unsigned char *)&szCpu1,(unsigned char *)(szCpu+4),4);
      bcopy((unsigned char *)&szCpu2,(unsigned char *)(szCpu+8),4);
      for(i = 0; i < 16; i++)
        printk("szCpu[%d]=%c\n",i,szCpu[i]);
    
        printk("cpu id is %u, info is %s\n", uCpuID,szCpu);
    }
    
    static int __init mymodule_init(void)
    {
      printk("Hello Kernel\n");
            get_CPUID();
      return 0;
    }
    
    static void __exit mymodule_exit(void)
    {
       printk ("Unloading my module.\n");
               return;
    }
    
    module_init(mymodule_init);
    module_exit(mymodule_exit);
    
    MODULE_LICENSE("GPL");
  3. 编译:编译的话,首先写哥makefile:
    obj-m += hello_kernel.o
    CUR_PATH := $(shell pwd)
    KERN_VER := $(shell uname -r)
    KERN_PATH := /usr/src/linux-headers-$(KERN_VER)
    all:
    		make -C ${KERN_PATH} M=${CUR_PATH} modules
    clean:
    		make -C ${KERN_PATH} M=${CUR_PATH} clean
  4. make,没有错误的话,可以通过下面命令将模块加载到内核。
    sudo insmod hello_kernel.ko
  5. 可以在dmesg或者cat /var/log/kern.log查看printk打印的信息。需要卸载模块的话,可以:
    sudo rmmod hello_kernel

更多更仔细的介绍的可以参看这篇文章(虽然中间有些说法现在直接用的话会有些问题。)



本文作者: Sigma    在新浪微博关注SigmaSigmaWeibo    RSS订阅本博客
本文链接: http://www.sigma.me/2011/11/15/linux-add-kernel-module.html
本博客采用知识共享署名—非商业性-禁止演绎使用3.0协议进行许可,转载请保留作者和原文链接。

  1. 2019年1月9日16:51 | #1

    Thanks for all your valuable hard work on this site. Gloria loves working on internet research and it’s easy to see why. Most people hear all concerning the lively method you deliver both interesting and useful guidance on this web blog and as well as inspire participation from other ones on this situation and our own simple princess is without question learning a whole lot. Have fun with the rest of the new year. You have been doing a stunning job.

  2. 2019年1月10日12:25 | #2

    Thanks for your entire work on this website. My niece delights in engaging in investigation and it’s simple to grasp why. Most people know all about the lively manner you present good items through your website and as well as foster contribution from people on that article then our favorite child has always been starting to learn a great deal. Enjoy the rest of the new year. You’re doing a stunning job.

  3. 2019年1月11日07:54 | #3

    I and also my pals happened to be digesting the nice tips and tricks from your web page then all of the sudden developed a terrible suspicion I had not thanked the website owner for those techniques. All the guys happened to be so stimulated to study them and have now without a doubt been making the most of these things. I appreciate you for turning out to be very thoughtful and then for figuring out variety of perfect guides millions of individuals are really needing to understand about. Our sincere apologies for not expressing appreciation to earlier.

  4. 2019年1月12日04:03 | #4

    Thank you for your own labor on this site. My daughter enjoys managing research and it’s obvious why. We all notice all regarding the lively ways you create informative guidelines on this website and therefore cause contribution from others about this matter so our princess has always been understanding a great deal. Take pleasure in the rest of the new year. You’re the one performing a good job.

  5. 2019年1月12日22:16 | #5

    My husband and i got quite joyful when Michael could do his reports through the precious recommendations he was given from your own web page. It is now and again perplexing to simply happen to be freely giving tips and tricks which often some others have been selling. Therefore we take into account we now have the blog owner to appreciate for this. These illustrations you’ve made, the easy web site navigation, the friendships you help create – it’s mostly terrific, and it’s assisting our son and us reckon that the subject is enjoyable, and that is pretty essential. Thank you for all the pieces!

  6. 2019年1月13日07:33 | #6

    I want to show my admiration for your generosity for folks who absolutely need help on the question. Your very own dedication to passing the message all through ended up being particularly helpful and has surely helped folks just like me to realize their goals. Your entire interesting information implies a whole lot to me and especially to my fellow workers. Many thanks; from each one of us.

  7. 2019年1月13日09:51 | #7

    I’m commenting to let you be aware of what a incredible encounter my wife’s child gained checking your site. She mastered a lot of issues, not to mention what it’s like to have an incredible giving mood to have most people clearly fully understand chosen grueling matters. You undoubtedly surpassed our own expected results. Thanks for showing such valuable, dependable, informative and even fun guidance on that topic to Evelyn.

  8. 2019年1月13日16:22 | #8

    My wife and i got happy that John managed to finish up his reports from your ideas he received from your own web page. It is now and again perplexing to simply choose to be giving away guidelines which the rest might have been making money from. And we fully grasp we now have the blog owner to appreciate for that. Those illustrations you have made, the easy web site navigation, the relationships you can make it easier to create – it’s got mostly astounding, and it’s really leading our son and our family know that that situation is fun, which is exceedingly mandatory. Thanks for the whole thing!

  9. 2019年1月14日10:17 | #9

    I’m also writing to make you know what a really good discovery my friend’s princess gained reading your web page. She figured out a good number of things, not to mention what it’s like to possess a wonderful teaching heart to make many more with no trouble know just exactly specified grueling matters. You actually did more than our desires. Thanks for giving those warm and helpful, safe, educational and in addition unique tips about the topic to Janet.

  10. 2019年1月14日19:48 | #10

    My wife and i felt very fortunate Chris managed to do his web research through the entire ideas he was given out of your weblog. It’s not at all simplistic to simply find yourself giving away concepts that most people might have been trying to sell. And we also realize we’ve got the website owner to appreciate for that. The type of illustrations you made, the straightforward blog menu, the friendships you can make it easier to engender – it’s most extraordinary, and it’s helping our son and our family do think that concept is enjoyable, which is incredibly important. Many thanks for all the pieces!

  11. 2019年1月15日05:54 | #11

    I precisely desired to thank you very much once more. I am not sure the things I would have followed without these creative ideas revealed by you on such a theme. It seemed to be the horrifying issue for me personally, nevertheless being able to see your expert tactic you dealt with it made me to jump with contentment. I will be happier for the work and in addition hope that you know what an amazing job you were undertaking training other individuals with the aid of a web site. I’m certain you’ve never met any of us.

  12. 2019年1月15日13:55 | #13

    I wish to show my admiration for your generosity for those people that require guidance on your concept. Your very own commitment to getting the solution across appeared to be extraordinarily advantageous and have specifically empowered girls just like me to achieve their dreams. Your entire informative hints and tips can mean much to me and far more to my mates. With thanks; from all of us.

  13. 2019年1月15日14:50 | #14

    Thanks a lot for providing individuals with an extremely pleasant opportunity to discover important secrets from here. It is often so lovely plus jam-packed with amusement for me personally and my office friends to search your site at the least thrice in one week to read through the new things you have. Not to mention, I’m just usually astounded concerning the striking tactics you serve. Selected 3 areas in this post are surely the finest we have had.

  14. 2019年1月16日07:46 | #15

    I enjoy you because of all your effort on this web page. Kate loves carrying out internet research and it’s obvious why. We all learn all regarding the powerful manner you present both interesting and useful information through the website and in addition encourage response from other ones on that situation while my girl is truly being taught a lot. Take pleasure in the remaining portion of the year. You are carrying out a dazzling job.

  15. 2019年1月16日16:14 | #16

    My wife and i got very more than happy that John could conclude his researching with the precious recommendations he obtained through the site. It is now and again perplexing to simply happen to be giving away tips and hints that the others have been trying to sell. And we fully grasp we need the blog owner to be grateful to because of that. Most of the illustrations you have made, the straightforward blog menu, the relationships your site aid to promote – it’s everything incredible, and it is letting our son in addition to our family consider that this subject matter is excellent, which is highly important. Thank you for the whole lot!

  16. 2019年1月17日03:13 | #17

    Thanks for each of your labor on this site. Gloria take interest in managing investigations and it’s simple to grasp why. A number of us learn all regarding the compelling way you create practical information on this website and as well as encourage participation from other individuals on this concept then my child is truly discovering a whole lot. Enjoy the rest of the year. You’re doing a brilliant job.

  17. 2019年1月17日10:49 | #18

    I enjoy you because of all of your efforts on this web site. My mom take interest in engaging in investigations and it’s easy to see why. My partner and i know all of the powerful ways you offer practical things through the web blog and therefore strongly encourage contribution from others on the subject matter then our favorite daughter is certainly understanding a whole lot. Have fun with the remaining portion of the new year. You’re conducting a stunning job.

  18. 2019年1月17日19:46 | #19

    I must express appreciation to the writer just for bailing me out of this circumstance. Just after searching through the the web and obtaining thoughts which are not productive, I believed my life was well over. Living minus the strategies to the difficulties you have solved by means of your report is a critical case, as well as those that might have in a negative way damaged my entire career if I hadn’t discovered your web page. Your know-how and kindness in taking care of all the pieces was very useful. I’m not sure what I would’ve done if I had not discovered such a thing like this. I’m able to at this point look ahead to my future. Thank you very much for this high quality and effective guide. I will not hesitate to suggest your web sites to anybody who needs guidelines on this problem.

  19. 2019年1月18日05:17 | #20

    I definitely wanted to develop a brief comment so as to express gratitude to you for these great tips and tricks you are showing at this website. My long internet look up has now been paid with good quality insight to write about with my best friends. I ‘d admit that many of us readers actually are undeniably endowed to live in a decent place with so many special individuals with valuable tricks. I feel truly lucky to have encountered your entire site and look forward to many more excellent minutes reading here. Thanks again for a lot of things.

  20. 2019年1月18日10:48 | #21

    I wanted to type a remark so as to say thanks to you for all of the nice recommendations you are placing on this site. My long internet research has at the end been compensated with awesome facts and techniques to share with my contacts. I ‘d believe that many of us site visitors are extremely endowed to be in a good network with many lovely individuals with insightful principles. I feel really grateful to have come across your entire web page and look forward to many more awesome times reading here. Thank you once more for a lot of things.

  21. 2019年1月18日12:19 | #22

    A lot of thanks for all of the labor on this site. My niece delights in getting into investigation and it’s really easy to understand why. Most of us learn all about the dynamic way you render priceless strategies by means of your web site and in addition increase participation from other individuals about this situation so our favorite child is undoubtedly discovering a great deal. Enjoy the rest of the year. Your carrying out a pretty cool job.

  22. 2019年1月19日05:29 | #23

    Thanks a lot for providing individuals with a very wonderful possiblity to read from this blog. It is always very pleasurable and as well , jam-packed with a lot of fun for me personally and my office colleagues to visit the blog particularly 3 times every week to find out the latest guides you will have. And of course, I’m also at all times happy with all the astounding techniques served by you. Some two tips on this page are really the most impressive we have had.

  23. 2019年1月19日12:42 | #24

    My wife and i ended up being absolutely contented Emmanuel managed to round up his web research out of the precious recommendations he had while using the web pages. It is now and again perplexing to simply find yourself giving freely secrets and techniques which other people could have been making money from. And we all consider we now have you to thank for that. The type of explanations you’ve made, the straightforward web site menu, the friendships you will aid to foster – it’s got most great, and it’s making our son in addition to the family believe that the article is excellent, and that’s exceptionally pressing. Thank you for all the pieces!

  24. 2019年1月19日22:20 | #25

    I wish to express some thanks to you for bailing me out of this particular condition. Right after scouting throughout the search engines and getting recommendations which are not powerful, I thought my entire life was over. Being alive devoid of the strategies to the difficulties you’ve fixed all through your good site is a crucial case, and the ones that could have negatively damaged my entire career if I had not discovered your web page. That skills and kindness in maneuvering almost everything was valuable. I’m not sure what I would have done if I had not encountered such a solution like this. I am able to at this point relish my future. Thanks so much for this professional and results-oriented help. I won’t think twice to propose the website to any individual who wants and needs care about this situation.

  25. 2019年1月20日06:15 | #26

    My wife and i felt really thrilled that Raymond managed to carry out his research using the ideas he got when using the web page. It’s not at all simplistic to simply always be releasing information and facts that people today may have been making money from. And we also remember we need you to be grateful to for this. The specific illustrations you’ve made, the easy blog menu, the friendships you can make it easier to engender – it is mostly fabulous, and it’s really facilitating our son in addition to us consider that that article is brilliant, which is rather mandatory. Many thanks for all the pieces!

  26. 2019年1月20日13:51 | #27

    I wanted to post you the very small remark to give thanks again for the pleasing suggestions you have featured at this time. It has been tremendously open-handed of you to make extensively precisely what most of us would have sold for an e-book to help with making some profit on their own, primarily since you might have done it if you considered necessary. The guidelines as well acted to become a easy way to fully grasp most people have the same dreams much like my very own to realize lots more when considering this condition. I know there are many more pleasurable periods in the future for many who find out your website.

  27. 2019年1月21日00:11 | #28

    I precisely desired to thank you very much once more. I’m not certain the things I would have achieved without these points provided by you concerning this area. It had become an absolute alarming condition in my position, nevertheless spending time with this skilled avenue you dealt with the issue made me to jump with gladness. I’m just grateful for this information and thus pray you really know what an amazing job you were undertaking instructing other individuals via a web site. Most likely you have never come across any of us.

  28. 2019年1月21日14:02 | #29

    Needed to compose you a tiny note to give many thanks once again for those pretty secrets you’ve discussed above. It’s pretty generous of people like you to present without restraint what a lot of people would’ve distributed as an e book to get some bucks for their own end, certainly seeing that you might well have tried it in the event you wanted. These guidelines additionally served to be a easy way to understand that some people have the identical zeal like mine to know a lot more when it comes to this condition. Certainly there are millions of more pleasant sessions ahead for people who take a look at your blog.

  29. 2019年1月22日08:03 | #30

    Needed to send you a very little observation just to thank you very much as before just for the fantastic basics you have shown in this article. This is quite tremendously generous of people like you to allow easily all that a lot of folks might have distributed as an electronic book to end up making some profit for their own end, principally given that you could possibly have tried it if you ever wanted. These concepts likewise acted as the great way to understand that most people have a similar desire the same as my own to know a great deal more around this problem. Certainly there are lots of more pleasurable times up front for people who view your site.

  30. 2019年1月22日16:16 | #31

    I enjoy you because of all your effort on this web site. Kate delights in carrying out investigations and it is simple to grasp why. We hear all of the compelling way you present effective tips and tricks through your blog and as well as welcome response from website visitors about this subject so our own princess has been studying so much. Take advantage of the rest of the new year. You’re performing a splendid job.

  1. 本文目前尚无任何 trackbacks 和 pingbacks.

无觅相关文章插件,快速提升流量