linux kernel "current" macro

本文探讨了Linux内核中的current宏使用方法及其内部实现原理,通过实例展示了如何利用current宏获取当前进程的信息,并深入剖析了task_struct结构,进一步解释了多核系统中current宏的正确操作方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-------------------------------source---------------------------------

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/tty.h>

/* 函数声明 */
void tty_write_message1(struct tty_struct *, char * );

/* 初始化函数 */
static int my_init( void )
{
        char *msg = "Hello tty!\n";
        printk( "hello, from the kernel...\n" );

        if( current != NULL )
                printk( "pid(command) = %d(%s) \n", current->pid,
                        current->comm );

}

 

 

/* 清理函数 */
static void my_cleanup( void )
{
        printk( "Goodbye, from the kernel ...\n" );
}


module_init( my_init );
module_exit( my_cleanup );

// this routine was borrowed from <printk.c>
void tty_write_message1( struct tty_struct *tty, char *msg )
{
        if( tty && tty->driver && tty->driver->ops && tty->driver->ops->write )
                tty->driver->ops->write( tty,  msg, strlen( msg) );

  // 写tty


        return ;
}

------------------------------output---------------------

$ sudo insmod currentptr.ko
Hello tty!

 

[ 1029.174761] hello, from the kernel...
[ 1029.174777] pid(command) = 2726(insmod)
[ 1029.174780] parent pid = 2725(sudo)
[ 1029.174782] parent parent pid = 7556(bash)
[ 1029.174784] parent parent parent pid = 7529(gnome-terminal)

 

----------------------------------------------------------------------------------------

在linux的内核的世界里, 有了current的个宏, 就可以去探索进程相关的代码

如: 打印进程列表

struct task_struct *task

for_each_process(task)
    {
        printk( KERN_WARNING "%8d%8ld%8d%s\n", task->pid,
            task->state, task->on_cpu, task->comm  );
    }   

 

---------------------------------------

[ 2597.598496]        1       1       0  init
[ 2597.598499]        2       1       0  kthreadd
[ 2597.598501]        3       1       0  ksoftirqd/0
[ 2597.598503]        6       1       0  migration/0
[ 2597.598506]        7       1       0  watchdog/0
[ 2597.598508]        8       1       0  migration/1

 

task_struct 是进程结构 这个结构的大小 大约是4k的大小 可见一个进程的结构关联了很多的信息, 而且这个结构中有大量的指针,

在 /include/asm-generic/current.h定义 不知道是否准确

0008 struct task_struct;
0009 
0010 DECLARE_PER_CPU(struct task_struct *, current_task);
0011 
0012 static __always_inline struct task_struct *get_current(void)
0013 {
0014     return this_cpu_read_stable(current_task);
0015 }
0016 
0017 #define current get_current()

如果给current赋值的话
current = NULL;
lvalue required as left operand of assignment
可以current 不是一个变量

在多核系统中怎么保证current 不会指向其他核上的宏呢
根据DECLARE_PER_CPUthis_cpu_read_stable 就可有知道一些信息


 




转载于:https://www.cnblogs.com/kwingmei/p/3731746.html

### Linux Kernel `get_current` Usage and Explanation In the context of the Linux kernel, obtaining information about the currently executing process is a common requirement. The macro or function used for this purpose is often referred to as `get_current`. This functionality allows developers to access details related to the current task or thread within the kernel space. The implementation of `get_current` leverages per-CPU variables which are designed specifically for scenarios where each processor has its own copy of certain data structures[^1]. By using these Per-CPU variables, accessing the current task structure becomes efficient because it avoids contention between CPUs in an SMP (Symmetric MultiProcessing) environment. Here’s how one might use `get_current`: ```c #include <linux/sched.h> struct task_struct *current_task; // Obtain pointer to the current running task. current_task = get_current(); ``` This code snippet demonstrates retrieving a pointer (`current_task`) pointing to the `task_struct`, representing the currently executing process on that particular CPU core at runtime. When dealing with preemption-aware kernels, ensuring correct behavior under all circumstances requires careful handling when referencing global state like the current task. Therefore, mechanisms such as RCU (Read-Copy Update), mentioned briefly earlier, play crucial roles alongside Per-CPU storage solutions provided by the operating system itself. Understanding what happens during a kernel oops can also provide insight into why proper management of tasks through constructs like `get_current` matters significantly for stability reasons. For instance, if there were issues while trying to manipulate pointers associated with the active task without adequate safeguards, encountering errors similar to those described could occur[^2]: An example output from a kernel panic includes various pieces of diagnostic information including but not limited to: - **Oops**: Indicates type of fault encountered; - **Page Error Code**: Describes nature of memory violation detected; - **Dead Counters & Affected CPU ID** : Tracks frequency and location specifics regarding failures across multiple cores; - **Process Identifier along with Command Name**: Identifies offending application causing instability; - **Instruction Pointer Address**: Points exactly where things went wrong inside executable instructions sequence being processed. --related questions-- 1. How does the scheduler manage processes efficiently? 2. What role do spinlocks play in managing concurrent operations safely? 3. Can you explain more about high-resolution timers' impact on real-time performance? 4. In what ways can improper usage of `get_current` lead to kernel panics?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值