gpt4 book ai didi

linux - Linux 内核代码中的 "current"

转载 作者:IT王子 更新时间:2023-10-28 23:57:34 25 4
gpt4 key购买 nike

当我浏览下面的 Linux 字符驱动程序代码块时,我在 printk 中找到了结构指针 current

我想知道 current 指向什么结构及其完整元素。

这个结构有什么作用?

ssize_t sleepy_read (struct file *filp, char __user *buf, size_t count, loff_t *pos)
{
printk(KERN_DEBUG "process %i (%s) going to sleep\n",
current->pid, current->comm);
wait_event_interruptible(wq, flag != 0);
flag = 0;
printk(KERN_DEBUG "awoken %i (%s)\n", current->pid, current->comm);
return 0;
}

最佳答案

它是指向当前进程的指针,即发出系统调用的进程。

来自docs :

The Current Process

Although kernel modules don't execute sequentially as applications do, most actions performed by the kernel are related to a specific process. Kernel code can know the current process driving it by accessing the global item current, a pointer to struct task_struct, which as of version 2.4 of the kernel is declared in <asm/current.h>, included by <linux/sched.h>. The current pointer refers to the user process currently executing. During the execution of a system call, such as open or read, the current process is the one that invoked the call. Kernel code can use process-specific information by using current, if it needs to do so. An example of this technique is presented in "Access Control on a Device File", in Chapter 5, "Enhanced Char Driver Operations".

Actually, current is not properly a global variable any more, like it was in the first Linux kernels. The developers optimized access to the structure describing the current process by hiding it in the stack page. You can look at the details of current in <asm/current.h>. While the code you'll look at might seem hairy, we must keep in mind that Linux is an SMP-compliant system, and a global variable simply won't work when you are dealing with multiple CPUs. The details of the implementation remain hidden to other kernel subsystems though, and a device driver can just include and refer to the current process.

From a module's point of view, current is just like the external reference printk. A module can refer to current wherever it sees fit. For example, the following statement prints the process ID and the command name of the current process by accessing certain fields in struct task_struct:

 printk("The process is \"%s\" (pid %i)\n",
current->comm, current->pid);

The command name stored in current->comm is the base name of the program file that is being executed by the current process.

关于linux - Linux 内核代码中的 "current",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com