在内核空间中调用times() [英] Calling times() in kernel space

查看:189
本文介绍了在内核空间中调用times()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个内核模块,我需要获得某个进程消耗的CPU时间的近似值(重复这些进程不是问题).具体来说,我希望libc clock times 系统调用.我尝试调用 do_sys_times ,但似乎未导出(编译时未定义的符号).

I am developing a kernel module, and I need to get an approximate value of the CPU time consumed by some process (iterating the processes is not an issue). Specifically, I want the same behavior provided by the libc clock or the times syscall. I tried calling do_sys_times but seems it's not exported (undefined symbol when compiled).

是否可以在内核模块中调用 times ?还有其他选择吗?

Is there a way to call times inside a kernel module? Are there any other alternatives?

推荐答案

如果要精确测量内核中某些事件之间的时间(例如上下文切换),则需要一些跟踪器,例如

If you want precisely measure times between some events in kernel (like context switching), you need some tracer, like SystemTap. From kernel module you may directly bind probes through various tracing and profiling subsystems like ftrace, perf or kprobes.

这里是一个在切换上下文时将消息转储到内核日志中的示例:

Here is an example which dumps message to kernel log when context is switched:

#include <linux/sched.h>
#include <linux/module.h>
#include <linux/printk.h>
#include <linux/tracepoint.h>

#include <trace/events/sched.h>

...

void my_sched_switch_probe(void* ignore, struct task_struct* prev, struct task_struct* next) {
    printk("my_sched_switch_probe: %s -> %s at %lu\n", prev->comm, next->comm, 
        (unsigned long) sched_clock());
}

int cswtracer_init(void) {
    register_trace_sched_switch(my_sched_switch_probe, NULL);

    return 0;
}

void cswtracer_fini(void) {
    unregister_trace_sched_switch(my_sched_switch_probe, NULL);
}

module_init(cswtracer_init);
module_exit(cswtracer_fini);

注意:不运行它,它将大大降低您的系统速度.

NOTE: do not run it, it will slow your system dramatically.

因此,分析my_sched_switch_probe()中的进程名称,并计算进程进入CPU(next->comm == "myprocessname")与离开CPU(prev->comm == "myprocessname")的时间之间的差.差异是CPU在此期间花费的最后时间.

So analyze name of processes in my_sched_switch_probe() and calculate difference between time when process entered CPU (next->comm == "myprocessname") and when it leaves CPU (prev->comm == "myprocessname"). That difference is the last time period process spent on CPU during.

这篇关于在内核空间中调用times()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆