编写Linux内核模块时获取用户进程pid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11915728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting user process pid when writing Linux Kernel Module
提问by
How can I get the PID of the user process which triggered my Kernel module's file_operation.read
routine (i.e., which process is reading /dev/mydev
) ?
如何获取触发我的内核模块file_operation.read
例程的用户进程的 PID (即,哪个进程正在读取/dev/mydev
)?
采纳答案by cnicutar
When your read function is executing, it's doing so in the context of the process that issued the system call. You should thus pe able to use current
, i.e. current->pid
.
当您的 read 函数正在执行时,它是在发出系统调用的进程的上下文中执行的。因此,您应该能够使用current
,即current->pid
。
回答by Yasushi Shoji
These days, we have some helper functions defined in sched.h. In the case of pid, you can use:
现在,我们在 sched.h 中定义了一些辅助函数。在 pid 的情况下,您可以使用:
pid = task_pid_nr(current);
to get the current task's pid.
获取当前任务的pid。
here is the comment taken from include/linux/sched.h
as of v3.8.
这是从include/linux/sched.h
v3.8 开始的评论。
the helpers to get the task's different pids as they are seen from various namespaces
- task_xid_nr() : global id, i.e. the id seen from the init namespace;
- task_xid_vnr() : virtual id, i.e. the id seen from the pid namespace of current.
- task_xid_nr_ns() : id seen from the ns specified;
- set_task_vxid() : assigns a virtual id to a task;
see also pid_nr() etc in include/linux/pid.h
获取任务的不同 pid 的助手,因为它们可以从各种命名空间中看到
- task_xid_nr() :全局id,即从init命名空间看到的id;
- task_xid_vnr() :虚拟id,即从current的pid命名空间看到的id。
- task_xid_nr_ns() :从指定的ns看到的id;
- set_task_vxid() :为任务分配一个虚拟 ID;
另请参见 include/linux/pid.h 中的 pid_nr() 等
回答by minghua
On a kernel 2.6.39 arm build, if current->pid
does not work then it may be done by:
在内核 2.6.39 arm 版本上,如果current->pid
不起作用,则可以通过以下方式完成:
pid_nr(get_task_pid(current, PIDTYPE_PID))
The PIDTYPE_PID
can be substituted by PIDTYPE_PGID
or PIDTYPE_SID
. The header source is at include/linux/pid.h
as Yasushi pointed out.
所述PIDTYPE_PID
可以通过取代PIDTYPE_PGID
或PIDTYPE_SID
。include/linux/pid.h
正如 Yasushi 所指出的,标题来源位于。
Which of the approaches work depends on what header files the code uses.
哪种方法有效取决于代码使用的头文件。