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) ?
3 Answers
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.
1 Comment
These days, we have some helper functions defined in sched.h. In the case of pid, you can use:
pid = task_pid_nr(current); to get the current task's pid.
here is the comment taken from include/linux/sched.h as of 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
Comments
On a kernel 2.6.39 arm build, if current->pid does not work then it may be done by:
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.
Which of the approaches work depends on what header files the code uses.