8

hi i have used sys_getpid() from within kernel to get process id how can I find out process name from kernel struct? does it exist in kernel??

thanks very much

Malesh N.
  • 83
  • 1
  • 1
  • 3

4 Answers4

16

struct task_struct contains a member called comm, it contains executable name excluding path.

Get current macro from this file will get you the name of the program that launched the current process (as in insmod / modprobe).

Using above info you can use get the name info.

jml
  • 53
  • 1
  • 7
Zimbabao
  • 8,150
  • 3
  • 29
  • 36
  • comm is a buffer of TAK_COMM_LENGTH which is a 16-byte buffer. In case the executable name is greater than 16 bytes, is there still a way (apart from filp_open of procfs) to get the complete task name? – Zoso Oct 25 '18 at 06:25
  • 2
    `current->comm` contains thread name. Which can be changed by pthread_setname_np or corresponding syscall. – Trishansh Bhardwaj Jul 01 '19 at 11:07
  • 1
    the links on this answer are now dead – NonCreature0714 Oct 08 '19 at 04:26
  • I can't edit the answer because the suggested edits queue is full, but I'd replace the dead lxr links with the ones from bootlin: https://elixir.bootlin.com/linux/v5.4/source/include/linux/sched.h#L624 – memememe Jun 30 '20 at 16:39
1

My kernel module loads with "modprobe -v my_module --allow-unsupported -o some-data" and I extract the "some-data" parameter. The following code gave me the entire command line, and here is how I parsed out the parameter of interest:

struct mm_struct *mm;
unsigned char x, cmdlen;

mm = get_task_mm(current);
down_read(&mm->mmap_sem);

cmdlen = mm->arg_end - mm->arg_start;
for(x=0; x<cmdlen; x++) {
    if(*(unsigned char *)(mm->arg_start + x) == '-' && *(unsigned char *)(mm->arg_start + (x+1)) == 'o') {
        break;
    }
}
up_read(&mm->mmap_sem);

if(x == cmdlen) {
    printk(KERN_ERR "inject: ERROR - no target specified\n");
    return -EINVAL;
}

strcpy(target,(unsigned char *)(mm->arg_start + (x+3)));

"target" holds the string after the -o parameter. You can compress this somewhat - the caller (in this case, modprobe) will be the first string in mm->arg_start - to suit your needs.

jml
  • 53
  • 1
  • 7
1

Not sure, but find_task_by_pid_ns might be useful.

Rumple Stiltskin
  • 9,597
  • 1
  • 20
  • 25
0

you can look at the special files in /proc/<pid>/

For example, /proc/<pid>/exe is a symlink pointing to the actual binary.

/proc/<pid>/cmdline is a null-delimited list of the command line, so the first word is the process name.

Ross Smith II
  • 11,799
  • 1
  • 38
  • 43
Foo Bah
  • 25,660
  • 5
  • 55
  • 79