Chinaunix首页 | 论坛 | 博客
  • 博客访问: 348688
  • 博文数量: 161
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 345
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-13 11:04
文章分类

全部博文(161)

文章存档

2015年(15)

2014年(144)

2013年(2)

我的朋友

分类: LINUX

2015-01-05 18:51:25

原文地址:linux中内核延时编程 作者:HYYLINUX

内核函数 ndelay, udelay, 以及 mdelay 对于短延时好用, 分别延后执行指定的纳秒数, 微秒数或者毫秒数. 它们涉及到的延时常常是最多几个毫秒。原型是:
#include
void ndelay(unsigned long nsecs);
void udelay(unsigned long usecs);
void mdelay(unsigned long msecs);

有另一个方法获得毫秒(和更长)延时而不用涉及到忙等待. 文件 声明这些函数:
void msleep(unsigned int millisecs);
unsigned long msleep_interruptible(unsigned int millisecs);
void ssleep(unsigned int seconds)

     前 2 个函数使调用进程进入睡眠给定的毫秒数.
一个对 msleep 的调用是不可中断的; 你能确保进程睡眠至少给定的毫秒数.
如果你的驱动位于一个等待队列并且你想唤醒来打断睡眠, 使用 msleep_interruptible. 从 msleep_interruptible 的返回值正常地是 0; 如果, 这个进程被提早唤醒, 返回值是在初始请求睡眠周期中剩余的毫秒数. 对 ssleep 的调用使进程进入一个不可中断的睡眠给定的秒数.
===========================================================================
#include
#include
#include

//定义使用定时来计时的宏
#ifndef SLEEP_MILLI_SEC
#define SLEEP_MILLI_SEC(nMilliSec)\
        do { \
                long timeout = (nMilliSec) * HZ / 1000; \
                while(timeout > 0) \
                { \
                timeout = schedule_timeout(timeout); \
                } \
        }while(0);
#endif


#define  error(...) do {\
    printk("********************************************************\n");\
    printk("error located %s : %d :%s\n",__FILE__,__LINE__,__FUNCTION__);\
    printk(__VA_ARGS__);\
    printk("********************************************************\n");\
}while(0)


static struct task_struct * MyThread = NULL;

static int MyPrintk(void *data)
{
    int i = 0;
    while (i>-1 ) {
        if (kthread_should_stop()) {
            break;
        }
        error(" i = %d\n",i);
//延时1000毫秒,在延时中一直占用CPU,不适合做长时间的延时,否则会导致内核或者系统出问题
//udelay(),ndelay()同理
        //mdelay(1000);  
//用定时来延时1000毫秒
        //SLEEP_MILLI_SEC(1000);
        msleep(1000);
        i++;
    }
    return 0;
}
static int __init init_kthread(void)
{
    MyThread = kthread_run(MyPrintk,"hello world","mythread");
    return 0;
}
static void __exit exit_kthread(void)
{
    if(MyThread)
    {
        printk("stop MyThread\n");
        kthread_stop(MyThread);
        MyThread = NULL;
    }
        return;
}
module_init(init_kthread);
module_exit(exit_kthread);
MODULE_AUTHOR("hyy");
MODULE_LICENSE("GPL");
阅读(1717) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~