通过内核模块轮询循环设备 [英] Polling a loop device through a kernel module

查看:90
本文介绍了通过内核模块轮询循环设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取我在200毫秒内通过内核模块创建的回送设备,但是当我尝试插入它时,它使内核崩溃.

I was trying to read a loopback device that I have created through a kernel module in periods of 200ms, but it is crashing the kernel, when I try to insert it.

我认为我的读取模块有问题,但是没有计时器就可以正常工作.

I think there is problem with my read module, but it works fine without timer.

我是内核编程的新手,请帮忙. 预先谢谢您:D

I am new to kernel programming,please help. Thank you in advance:D

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/timer.h>
#include<linux/fs.h>
#include <linux/init.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

static struct timer_list my_timer;

static void read_file(char *filename)
{
  struct file *fd;
  char buf[1];
  unsigned long long offset=0;
  mm_segment_t old_fs = get_fs();
  set_fs(KERNEL_DS);

  fd = filp_open(filename, O_RDONLY, 0);
  if (fd >= 0) {
    printk(KERN_DEBUG);
    while (vfs_read(fd, buf, 1,&offset) == 1)
    {
      if((0 <= buf[0]) && (buf[0] <=255))
        printk("%c", buf[0]);
    } 
    printk(KERN_ALERT "Loop Ran\n");
    filp_close(fd,NULL);
  }
  set_fs(old_fs);
}

void my_timer_callback( unsigned long data )
{
  int ret;
  printk( "my_timer_callback called (%ld).\n", jiffies );  
  printk( "Starting timer to fire in 200ms (%ld)\n", jiffies );  
  read_file("/dev/loop0");  
  ret = mod_timer( &my_timer, jiffies + msecs_to_jiffies(3000) );
  if(ret)  
    printk("Error in mod_timer\n");  
}

int init_module( void )
{
  int ret;
  printk("Timer module installing\n");

  setup_timer( &my_timer, my_timer_callback, 0 );

  printk( "Starting timer to fire in 200ms (%ld)\n", jiffies );
  ret = mod_timer( &my_timer, jiffies + msecs_to_jiffies(200) );
  if(ret)
    printk("Error in mod_timer\n");

  return 0;
}

void cleanup_module( void )
{
  int ret;

  ret = del_timer( &my_timer );
  if(ret)
    printk("The timer is still in use...\n");

  printk("Timer module uninstalling\n");

  return;
}`enter code here`

MODULE_LICENSE("GPL"); 

我的Make文件:

obj-m := timer2.o
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD)   clean 

推荐答案

内核计时器函数应该是原子的.文件操作需要流程上下文.崩溃是由于读取操作中存在文件操作所致.

Kernel timer functions should be atomic. File operations need a process context. Your crash is due to file operations present in you read operation.

Linux设备驱动程序-第7章应该让您了解内核计时器.

Linux device drivers - chapter 7 should get you going on kernel timers.

这篇关于通过内核模块轮询循环设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆