内核5.1使用delayed_work 例子

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/leds.h>

#include <linux/gpio.h>

static struct timer_list tm;
static struct delayed_work delay_amov;

static void time_callback(struct timer_list *arg);

static void delay_work_func(struct work_struct *work)
{
    gpio_set_value(318,1);
}
static void time_callback(struct timer_list *arg)
{
    gpio_set_value(318,0);
    schedule_delayed_work(&delay_amov, msecs_to_jiffies(1000-2));	
    tm.expires = jiffies+1*HZ;
    add_timer(&tm); 
}

static int __init demo_init(void)
{
 
    timer_setup(&tm,time_callback,0);
    
    tm.expires = jiffies + 1*HZ;
    add_timer(&tm);
    gpio_set_value(318,1);   

    if(gpio_request(318,"amov_led"))
    {
        printk("led request error \n");
    }
    if(gpio_direction_output(318, 1))
    {
        printk("led set direction error \n");
    }
    gpio_set_value(318,1);

    INIT_DELAYED_WORK(&delay_amov, delay_work_func);

    return 0;
}
static void __exit demo_exit(void)
{
    gpio_free(318);
    del_timer(&tm);        
}
module_init(demo_init);
module_exit(demo_exit);
 
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Farsight");
MODULE_DESCRIPTION("Demo for kernel module");
Linux内核中,`INIT_DELAYED_WORK` 是一个用于初始化延迟工作的宏。它通常与工作队列(workqueue)机制一起使用,用于延迟执行某些任务。延迟工作允许开发者在未来的某个时间点执行特定的操作,而不是立即执行。 以下是 `INIT_DELAYED_WORK` 的基本用法和解释: 1. **定义工作结构体**: 首先,需要定义一个 `struct delayed_work` 结构体,用于描述延迟工作。 ```c struct delayed_work my_work; ``` 2. **初始化工作结构体**: 使用 `INIT_DELAYED_WORK` 宏初始化工作结构体,并指定工作处理函数。 ```c INIT_DELAYED_WORK(&my_work, my_work_handler); ``` 其中,`my_work_handler` 是指向工作处理函数的指针。 3. **定义工作处理函数**: 定义一个工作处理函数,该函数将在延迟时间到达后执行。 ```c void my_work_handler(struct work_struct *work) { // 在这里执行延迟任务 } ``` 4. **调度延迟工作**: 使用 `schedule_delayed_work` 函数将延迟工作添加到工作队列中,并指定延迟时间。 ```c schedule_delayed_work(&my_work, delay_in_jiffies); ``` 其中,`delay_in_jiffies` 是延迟的时间,以jiffies为单位。 5. **取消延迟工作**: 如果需要,可以在延迟时间到达之前取消延迟工作。 ```c cancel_delayed_work(&my_work); ``` 通过以上步骤,可以在Linux内核使用 `INIT_DELAYED_WORK` 宏来初始化和调度延迟工作,从而实现任务的延迟执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值