编写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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:03:43  来源:igfitidea点击:

Getting user process pid when writing Linux Kernel Module

clinuxkernel-module

提问by

How can I get the PID of the user process which triggered my Kernel module's file_operation.readroutine (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.has of v3.8.

这是从include/linux/sched.hv3.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->piddoes not work then it may be done by:

在内核 2.6.39 arm 版本上,如果current->pid不起作用,则可以通过以下方式完成:

    pid_nr(get_task_pid(current, PIDTYPE_PID))

The PIDTYPE_PIDcan be substituted by PIDTYPE_PGIDor PIDTYPE_SID. The header source is at include/linux/pid.has Yasushi pointed out.

所述PIDTYPE_PID可以通过取代PIDTYPE_PGIDPIDTYPE_SIDinclude/linux/pid.h正如 Yasushi 所指出的,标题来源位于。

Which of the approaches work depends on what header files the code uses.

哪种方法有效取决于代码使用的头文件。