linux从内核中的pid获取进程名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5406942/
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-05 03:22:50  来源:igfitidea点击:

linux get process name from pid within kernel

linuxlinux-kernel

提问by Malesh N.

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??

嗨,我在内核中使用了 sys_getpid() 来获取进程 ID 如何从内核结构中找出进程名称?它存在于内核中吗?

thanks very much

非常感谢

采纳答案by Zimbabao

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

struct task_struct包含一个名为comm的成员,它包含executable name excluding path.

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

从此文件中获取当前宏将为您提供启动当前进程的程序的名称(如 insmod / modprobe)。

Using above info you can use get the name info.

使用上述信息,您可以使用获取名称信息。

回答by Rumple Stiltskin

Not sure, but find_task_by_pid_nsmight be useful.

不确定,但find_task_by_pid_ns可能有用。

回答by Foo Bah

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

你可以看看特殊文件 /proc/<pid>/

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

例如,/proc/<pid>/exe是指向实际二进制文件的符号链接。

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

/proc/<pid>/cmdline是一个空分隔的命令行列表,所以第一个词是进程名称。

回答by jml

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:

我的内核模块加载了“modprobe -v my_module --allow-unsupported -o some-data”,然后我提取了“some-data”参数。下面的代码给了我整个命令行,这里是我解析出感兴趣的参数的方法:

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.

“target”保存 -o 参数后的字符串。您可以稍微压缩一下 - 调用者(在本例中为 modprobe)将是 mm->arg_start 中的第一个字符串 - 以满足您的需要。