初识内核进程--linux进程管理-1

相关接口:

kthread_creat

kthread_run=kthread_creat + wake_up_process

kthread_stop

kthread_should_stop

fork

do_fork

vfork

clone

 

示例:

1- kthread_create

#include<linux/init.h>
#include<linux/module.h>
#include <linux/sched.h> 
#include <linux/kthread.h>
#include <linux/err.h>

MODULE_LICENSE("Dual BSD/GPL");

static struct task_struct *test_task;

static int test_thread(void *data)
{
	int cnt = 0;
	while(!kthread_should_stop())
	{
		set_current_state(TASK_UNINTERRUPTIBLE);
		printk("thread run cnt : %d\n", cnt);
		cnt++;
		schedule_timeout(HZ);		
	}

	return 0;
}

static int hello_init(void)
{
    printk(KERN_ALERT "HELLLO WORLD ENTER! \n");
	
	test_task = kthread_create(test_thread, NULL, "test_task"); 
    if(IS_ERR(test_task)){    
       
      pr_err("Failed to create thread.\n");
	  return PTR_ERR(test_task);   
    }  	
	wake_up_process(test_task);
	
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "HELLO WORLD EXIT! \n");
	
    if(test_task){    
        printk("stop MyThread\n");
		kthread_stop(test_task);    
        test_task = NULL;   
    }
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_AUTHOR("LHK");

 

 

2- kthread_run

#include<linux/init.h>
#include<linux/module.h>
#include <linux/sched.h> 
#include <linux/kthread.h>
#include <linux/err.h>

MODULE_LICENSE("Dual BSD/GPL");

static struct task_struct *test_task;

static int test_thread(void *data)
{
	int cnt = 0;
	while(!kthread_should_stop())
	{
		set_current_state(TASK_UNINTERRUPTIBLE);
		printk("thread run cnt : %d\n", cnt);
		cnt++;
		schedule_timeout(HZ);
		
	}

	return 0;
}

static int hello_init(void)
{
    printk(KERN_ALERT "HELLLO WORLD ENTER! \n");
	
	test_task = kthread_run(test_thread,NULL,"test_task");
	if(IS_ERR(test_task)){    
	   
	  pr_err("Failed to create thread.\n");
	  return PTR_ERR(test_task);   
	}  		
	
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "HELLO WORLD EXIT! \n");
	
    if(test_task){    
        printk("stop MyThread\n");
		kthread_stop(test_task);    
        test_task = NULL;   
    }
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_AUTHOR("LHK");

 

 

 

 

 

 

 

 

 

 

 

 

参考:

https://www.cnblogs.com/zhangxuechao/p/11709830.html

http://blog.sina.com.cn/s/blog_6237dcca0100gq67.html

linux内核设计与实现第3章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值