歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux 驅動與安裝:教你學會編寫Linux設備驅動

Linux 驅動與安裝:教你學會編寫Linux設備驅動

日期:2017/2/25 10:39:53   编辑:Linux教程
 內核版本: 2.4.22

  閱讀此文的目的: 學會編寫Linux設備驅動。

  閱讀此文的方法: 閱讀以下2個文件: hello.c,asdf.c。

  此文假設讀者:

  已經能用C語言編寫Linux應用程序,

  理解"字符設備文件, 塊設備文件, 主設備號, 次設備號",

  會寫簡單的Shell腳本和Makefile。

  1. "hello.c"

  --------------------------------

  /*

  * 這是我們的第一個源文件,

  * 它是一個可以加載的內核模塊,

  * 加載時顯示"Hello,World!",

  * 卸載時顯示"Bye!"。

  * 需要說明一點,寫內核或內核模塊不能用寫應用程序時的系統調用或函數庫,

  * 因為我們寫的就是為應用程序提供系統調用的代碼。

  * 內核有專用的函數庫,如, , 等,

  * 現在還沒必要了解得很詳細,

  * 這裡用到的printk的功能類似於printf。

  * "/usr/src/linux"是你實際的內核源碼目錄的一個符號鏈接,

  * 如果沒有現在就創建一個,因為下面和以後都會用到。

  * 編譯它用"gcc -c -I/usr/src/linux/include hello.c",

  * 如果正常會生成文件hello.o,

  * 加載它用"insmod hello.o",

  * 只有在文本終端下才能看到輸出。

  * 卸載它用"rmmod hello"

  */

  /*

  * 小技巧: 在用戶目錄的.bashrc裡加上一行:

  * alias mkmod='gcc -c -I/usr/src/linux/include'

  * 然後重新登陸Shell,

  * 以後就可以用"mkmod hello.c"的方式來編譯內核模塊了。

  */

  /* 開始例行公事 */

  #ifndef __KERNEL__

  # define __KERNEL__

  #endif

  #ifndef MODULE

  # define MODULE

  #endif

  #include

  #include

  MODULE_LICENSE("GPL");

  #ifdef CONFIG_SMP

  #define __SMP__

  #endif

  /* 結束例行公事 */

  #include /* printk()在這個文件裡 */

  static int

  init_module

  (){

  printk("Hello,World!\n");

  return 0; /* 如果初始工作失敗,就返回非0 */

  }

  static void

  cleanup_module

  (){

  printk("Bye!\n");

  }

  ------------------------------------

  2. "asdf.c"

  ------------------------------------

 struct file *filp,

  char *buf,

  size_t count,

  loff_t *f_pos

  ){

  loff_t pos;

  pos = *f_pos; /* 文件的讀寫位置 */

  if ((pos==4096) || (count>4096)) return 0; /* 判斷是否已經到設備尾,或寫的長度超過設備大小 */

  pos += count;

  if (pos > 4096) {

  count -= (pos - 4096);

  pos = 4096;

  }

  if (copy_to_user(buf, asdf_body+*f_pos, count)) return -EFAULT; /* 把數據寫到應用程序空間 */

  *f_pos = pos; /* 改變文件的讀寫位置 */

  return count; /* 返回讀到的字節數 */

  }

  static ssize_t

  asdf_write /* write回調,和read一一對應 */

  (

  struct file *filp,

  const char *buf,

  size_t count,

  loff_t *f_pos

  ){

  loff_t pos;

  pos = *f_pos;

  if ((pos==4096) || (count>4096)) return 0;

  pos += count;

  if (pos > 4096) {

  count -= (pos - 4096);

  pos = 4096;

  }

  if (copy_from_user(asdf_body+*f_pos, buf, count)) return -EFAULT;

  *f_pos = pos;

  return count;

  }

  static loff_t

  asdf_lseek /* lseek回調 */

  (

  struct file * file,

  loff_t offset,

  int orig

  ){

  loff_t pos;

  pos = file->f_pos;

  switch (orig) {

  case 0:

  pos = offset;

  break;

  case 1:

  pos += offset;

  break;

  case 2:

  pos = 4096+offset;

  break;

  default:

  return -EINVAL;

  }

  if ((pos>4096) || (pos<0)) {

  printk("^_^ : lseek error %d\n",pos);

  return -EINVAL;

  }

  return file->f_pos = pos;

  }

Copyright © Linux教程網 All Rights Reserved