Getting user process pid when writing Linux Kernel Module Getting user process pid when writing Linux Kernel Module linux linux

Getting user process pid when writing Linux Kernel Module


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.


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


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.