Linux内核 kthread_create_on_node()

函数:kthread_create_on_node( )

文件包含:

        #include <linux/kthread.h>

函数定义:

在内核源码中的位置:linux-3.19.3/kernel/kthread.c

函数定义格式:

struct task_struct kthread_create_on_node (int (*threadfn)(void * data), void* data, int node, const char namefmt[], ...)

函数功能描述:

此函数用于在指定存储节点上创建一个新的内核线程。

函数实现过程:首先在内核地址空间为此进程分配内存空间,然后初始化与此进程相关的变量,将该线程添加到内核线程列表中,并返回新进程的进程描述信息。

输入参数说明:

  • 参数int (*threadfn) (void *data)是一个函数指针,即它是一个函数,此函数是此进程执行时执行的函数,此函数返回值为int型,参数是一个void型指针。

  • 参数void * data是一个void型指针,是传递给第一个参数所代表函数的参数,即进程执行时函数的参数。

  • 参数node为存储节点编号,内核将内存区域进程编号,如果指定编号,则创建的新进程在指定的内存区域,如果不指定,设置为-1,则内核随机选择内存区域。

  • namefmt为进程的输出类型名。

返回参数说明:

参数task是struct task_struct型变量,保存任务的基本信息,其定义在文件linux-3.19.3/include/linux/sched.h,内核源码注释比较详细。

实例解析:

编写测试文件:kthread_create_on_node.c

头文件引用:

#include <linux/module.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/wait.h>
#include <linux/kthread.h>
MODULE_LICENSE("GPL");

新进程执行的函数定义:

int my_function(void * argc)
{
    printk("in the kernel thread function! \n");
    printk("the current pid is:%d\n", current->pid);     //显示当前进程的PID值
    printk("out the kernel thread function\n");
    return 0;
}

模块加载函数定义:

static int __init kthread_create_on_node_init(void)
{
    struct task_struct * result;
    printk("into kthread_create_on_node_init.\n");
    // 创建新进程
    result=kthread_create_on_node(my_function, NULL, -1, "kthread_create_on_node_init.c");
    printk("the pid of the new thread is:%d\n", result->pid); //显示新线程的PID值
    wake_up_process(result);                                      //唤醒新创建的线程
    printk("the current pid is:%d\n", current->pid);              //显示当前进程的PID值
    printk("out kthread_create_on_node_init.\n");
    return 0;
}

模块退出函数定义:

static void __exit kthread_create_on_node_exit(void)
{
    printk("Goodbye kthread_create_on_node\n");
}

模块加载、退出函数调用:

module_init(kthread_create_on_node_init);
module_exit(kthread_create_on_node_exit);

实例运行结果及分析:

首先编译模块,执行命令insmod kthread_create_on_node.ko插入模块,然后执行命令dmesg -c查看内核输出信息,会出现如图所示的结果。

Linux内核 kthread_create_on_node()

结果分析:

上图说明创建新进程成功,当前进程的进程号是6754,新创建进程的进程号是6755,在新进程创建完成之后,执行函数wake_up_process( )唤醒新进程,执行新进程,输出结果显示新进程对应的函数能够被成功执行。

酷客网相关文章:

赞(1)

评论 抢沙发

评论前必须登录!