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

摘要:本文介绍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 );
}
posted @ 2015-12-16 14:36  ddk3000  阅读(2344)  评论(0编辑  收藏  举报