linux内核cpu占用高,linux内核线程cpu占用100%?!

在项目中遇到内核线程占用几乎100%的现象,而且内核模块不可卸载。在查找资料之后,一个可行的模板如下:

#include

#include

#include

#include

#include

#include

#include

#include

#include // for DECLARE_COMPLETION()

#include

#include // mdelay()

#include

MODULE_LICENSE("GPL");

static DECLARE_COMPLETION(my_completion);

static struct task_struct *task;

int flag = 0;

int my_fuction(void *arg)

{

printk(" in %s()\n", __FUNCTION__);

allow_signal(SIGKILL); //使得线程可以接收SIGKILL信号

mdelay(2000);

printk(" my_function complete()\n");

printk("should stop: %d\n",kthread_should_stop());

while (!signal_pending(current) && !kthread_should_stop()) {//使得线程可以可以被杀死,也可以在rmmod的时候结束

printk(" jiffies is %lu\n", jiffies);

set_current_state(TASK_INTERRUPTIBLE);// 将该进程的状态从执行状态TASK_RUNNING 变成睡眠状态TASK_INTERRUPTIBLE

schedule_timeout(HZ * 5); //对当前进程调用schedule,并在指定的时间到期后(timeout了)将进程唤醒,参见schedule_timeout实现源码。可以自行将这个值调小。

printk("should stop: %d\n",kthread_should_stop());

}

printk("Leaving my_function\n");

flag = 1; //flag很关键!

return 0;

}

static int __init init(void)

{

task = kthread_run(my_fuction,NULL,"my_function");

printk("<1> init wait_for_completion()\n");

return 0;

}

static void __exit finish(void)

{

int ret;

if(!flag)

{

if (!IS_ERR(task))

{

int ret = kthread_stop(task);

printk(KERN_INFO "First thread function has stopped ,return %d\n", ret);

}

}

printk("task_struct: 0x%x",task);

printk(" Goodbye\n");

}

module_init(init);

module_exit(finish);

参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值