Take the 2-minute tour ×

How can I get the PID of the user process which triggered my kernel module's file_operation.read routine (ie which process is reading /dev/mydev) ?

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

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.

share|improve this answer
Thanks, works ok –  Nada nada Aug 11 '12 at 15:11
what is current? read doesn't get a current as argument... ssize_t(*read) (struct file *, char __user *, size_t, loff_t *); –  0x90 Aug 11 '12 at 15:30
@0x90 It's a macro. –  cnicutar Aug 11 '12 at 15:41
kernelnewbies.org/FAQ/current ,right? –  0x90 Aug 11 '12 at 15:54
@0x90 That's the one. –  cnicutar Aug 11 '12 at 15:58
add 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

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


