获取内核中当前运行程序的绝对路径

为了检索正在运行的程序的文件权限,我需要在当前运行的程序上执行kstat 。 然后我需要获取加载的ELF图像的绝对路径。

那可能吗? current->comm仅记录没有路径的程序名称。

或者其他什么方法呢?

您可以使用/proc/self/exe的路径readlink(2) ,在您的情况下,它将是ELF的链接。 使用readlink(1)

 $ readlink /proc/self/exe /bin/readlink 

据我所知,仅限Linux。

proc文件系统在/proc//exe返回此信息,因此您需要执行类似的操作。

proc获取fs/proc/base.c函数proc_exe_link中进程的路径。 此函数改编自proc_exe_link

 char *get_current_proc_path(char *buf, int buflen) { struct file *exe_file; char *result = ERR_PTR(-ENOENT); struct mm_struct *mm; mm = get_task_mm(current); if (!mm) { goto out; } down_read(&mm->mmap_sem); exe_file = mm->exe_file; if (exe_file) { get_file(exe_file); path_get(&exe_file->f_path); } up_read(&mm->mmap_sem); mmput(mm); if (exe_file) { result = d_path(&exe_file->f_path, buf, buflen); path_put(&exe_file->f_path); fput(exe_file); } out: return result; } 

这会将路径放在buf某个位置(不一定是缓冲区的开头),并返回指向路径的指针。 出错时,它将返回ERR_PTR ,因此检查指针是否对IS_ERR有效。

你的意思是getcwd()? http://man7.org/linux/man-pages/man2/getcwd.2.html

 #include  char * getcwd(char * buf, size_t size); 

– – – – – – – – – 编辑 – – – – – – – – – – –

你想检查另一个正在运行的程序的路径,你可以在/ proc / $ PID / exe中找到它:

 ll /proc/$PID/exe 

要么

 ll /proc/$PID | grep exe 

要么

 readlink /proc/$PID/exe 
 Table 1-5: Kernel info in /proc .............................................................................. File Content apm Advanced power management info buddyinfo Kernel memory allocator information (see text) (2.5) bus Directory containing bus specific information **cmdline** Kernel command line 

防爆。

 [root@localhost ~]# more /proc/364/cmdline /usr/sbin/smbd [root@localhost ~]# more /proc/364/common /proc/364/common: No such file or directory [root@localhost ~]# more /proc/364/comm smbd [root@localhost ~]#