The first experiment for getting started with Linux kernel drivers: Globalvar driver

Source: Internet
Author: User

First, the driver file is written, the name of the file named Globalvar.c, the source code is as follows:

#include  <linux/module.h> //supports dynamic loading and unloading of module header files #include <linux/init.h> //the most basic header files, The kernel initializes the #include <linux/fs.h>  //file system header file, including device registration functions and logoff functions #include <asm/uaccess.h>  //declares the header file Module_license ("GPL") for functions that move data between kernel code and user space,  //module license #define major_num 1025 // Main device number #define device_name  "Globalvar"  //device name static char drv_buf[1024]; //********* Defines the Read method ********************************static ssize_t globalvar_read (struct  file *filp, const char *buf ,ssize_t len, loff_t *off) {//Will Drv_ BUF data is copied from kernel space to user space      if  (copy_to_user (buf, drv_buf, sizeof (int)))       {          return -  efault;     }    return sizeof (int);} Defining the Write Method * *Static ssize_t globalvar_write (struct file *filp,const char  *buf,ssize_t len) {//copy data from user space to kernel space     if  (Copy_from_user (Drv_buf, buf,  sizeof (int)))     {        return -  efault;    }    return sizeof (int);} Initialize device-driven  file_operations  structural body **********struct file_operations globalvar_fops  ={     .owner = this_module,     .read =  globalvar_read,     .write = globalvar_write,};//************ Module Initialization function * Static int __init globalvar_init (void) {    int ret;     //Registered device driver     ret = register_chrdev (MAJOR_NUM, DEVICE _name, &globalvar_fops);     if  (ret) &NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTK (" Globalvar register failure ");    }    else    &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTK ("globalvar register success");     }    return ret;} Module unload function **********************static void __exit globalvar_exit (void) {      //Logoff device driver      unregister_chrdev (major_num,  "Globalvar");  //Note that the Unregister_chrdev function in the new version of the kernel is a &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTK with no return value (" globalvar  unregister success! \ n ");} Module_init (Globalvar_init); Module_exit (Globalvar_exit);

Driver writing and debugging, especially the driver debugging process will encounter a lot of problems, sometimes you follow the code in the book, compile the error, because the new kernel version and the old kernel version of some functions and mechanisms will be somewhat different, such as the above program, Module unload function inside the Unregister_chrdev in the new kernel version is no return value, so do not allow other parameters and this function has an assignment relationship, once there is an assignment relationship, the compilation will error! Encounter problems to calm, more Baidu, more advice!


Second, write the makefile file:

obj-m:=globalvar.odefault:$ (make)-c/lib/modules/$ (shell uname-r)/build m=$ (PWD) modulesclean:$ (make)-c/lib/ modules/$ (Shell uname-r)/build m=$ (PWD) Clean

This makefile file is common for compiling other modules, so you can compile other modules you want to compile by simply changing the first line's Globalvar name. Note that the code under default and clean starts with the TAB key.


Third, compile the Globalvar module

Put the previous globalvar.c file and the makefile file in the same folder, I was placed in the Globalvar folder I created, go to the Globalvar folder, open the terminal, and then log in root permissions, enter the make command compile module.


Four, write the test program of the Globalvar module, name it test_globalvar.c, the source code is as follows:

#include <stdlib.h> #include  <stdio.h> #include  <fcntl.h>void showbuf (int * BUF); Int main (void) {     int fd,i;     int  Buf[100];     for (i=0;i !=100;++i)      {       buf[i]=i;     }      //Open the/dev/ Globalvar "     fd = open ("/dev/globalvar ",  o_rdwr, s_irusr | &NBSP;S_IWUSR);      printf ("the fd is :%d \n", FD);      if  (fd != -1 )      {        printf ("Write%d  number to/dev/globalvar: \ n", +);        Showbuf (BUF);        write (fd,buf,100);        printf ("from/dev/globalvar reads%d  numbers: \ n ", +);        read (fd,buf,100);        showbuf (BUF);        close (FD);       }      else     {            printf ("device globalvar open failure\n");       }     return 0;} Void showbuf (int *buf) {    int i,j=0;    for (i=0;i< 100;i++)     {        if (i%5==0)              printf ("\n%4d:", J + +);         printf ("%4d", Buf[i]);     }    printf ("\n************ \ n ");}

Compile the test file in the terminal input Directive Gcc-o TEST_GLOBALVAR.O test_globalvar.c.


v. , load the Globalvar module with the insmod instruction, enter Insmod Globalvar.ko in the terminal,


Six, using the MKNOD directive to establish the corresponding index node of the directory entry and file, in the terminal input instruction Mknod/dev/globalvar C 1025 0

< Span style= "Color:rgb (51,51,51); Font-family:arial;font-size:14px;line-height:26px;background-color:rgb ( 255,255,255); " >

< Span style= "Color:rgb (51,51,51); Font-family:arial;font-size:14px;line-height:26px;background-color:rgb ( 255,255,255); " > Seven, test equipment Globalvar, enter the command at the terminal./test_globalvar can see that we first write 100 numbers to the character device Globalvar, and then the character device Globalvar reads the 100 numbers that are written, The data exchange between devices is realized.




This article is from the "Stop Thinking" blog, make sure to keep this source http://9110091.blog.51cto.com/9100091/1546961

The first experiment for getting started with Linux kernel drivers: Globalvar driver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.