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 ); }