取当前进程对应之静态映像文件的绝对路径/proc/self/exe

提供一个linux  advanced programming 上的得到绝对路径目录的函数:
char* get_self_executable_directory ()
{
  int rval;
  char link_target[1024];//目标地址
  char* last_slash;
  size_t result_length;//结果的长度
  char* result;

  /* Read the target of the symbolic link /proc/self/exe.  */
读取绝对路径
  rval = readlink ("/proc/self/exe", link_target, sizeof (link_target) - 1);
  if (rval == -1)
    /* The call to readlink failed, so bail.  */
    abort ();
  else
    /* NUL-terminate the target.  */
    link_target[rval] = '\0';
  /* We want to trim the name of the executable file, to obtain the
     directory that contains it.  Find the rightmost slash.  */
找到最后一个/
  last_slash = strrchr (link_target, '/');
如果是空或者是以/开头,则退出
  if (last_slash == NULL || last_slash == link_target)
    /* Something stange is going on.  */
    abort ();
last_slash保存的是最后的/的地址
  /* Allocate a buffer to hold the resulting path.  */
link_target开始的地址
  result_length = last_slash - link_target;
  result = (char*) xmalloc (result_length + 1);
  /* Copy the result.  */
  strncpy (result, link_target, result_length);
  result[result_length] = '\0';
  return result;
}

同时可以用以下程序得到绝对路径
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAXBUFSIZE 1024

int main ( int argc, char * argv[] )
{
    char buf[ MAXBUFSIZE ];
    int  count;

    count = readlink( "/proc/self/exe", buf, MAXBUFSIZE );
    if ( count < 0 || count >= MAXBUFSIZE )
    {
        printf( "Failed\n" );
       return( EXIT_FAILURE );
    }
    buf[ count ] = '\0';
    printf( "/proc/self/exe -> [%s]\n", buf );
    return( EXIT_SUCCESS );
}   
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值