Linux:获取当前进程的执行文件的绝对路径

from:https://www.cnblogs.com/ddk3000/p/5051111.html

摘要:本文介绍Linux的应用程序和内核模块获取当前进程执行文件绝对路径的实现方法。

注意:使用此方法时,如果执行一个指向执行文件的链接文件,则获得的不是链接文件的绝对路径,而是执行文件的绝对路径。

应用程序的实现方法

#include <stdio.h>
#include <unistd.h> int main( ) { char link[100]; char path[100]; sprintf( link, "/proc/%d/exe", getpid() ); int i = readlink( link, path, sizeof( path ) ); path[i] = '\0'; printf( "%s : %d\n", path, getpid() ); return 0; } 

内核模块的实现方法

#include <linux/namei.h>
#include <linux/dcache.h> char *ptr; char link[100], buf[256]; struct path path; sprintf( link, "/proc/%d/exe", current->pid ); int err = kern_path( link, LOOKUP_FOLLOW, &path ); if ( !err ) { ptr = d_path( &path, buf, 256 ); if ( !IS_ERR( ptr ) ) { // prt contains real path } path_put( &path ); }

猜你喜欢

转载自www.cnblogs.com/pangkr-linux/p/12888778.html