linux命令 执行exe文件路径,Linux下获取当前进程的执行文件的绝对路径和所在目录(通过/proc/self/exe链接)...

#include

#include   //strrchr(),

strncpy()

#include

//realloc()

#include

//readlink()

#define MAXBUFSIZE

1024

//通过链接文件名获取被目标文件绝对路径

//为了防止buffer不够大,包装一下readlink()

char*

getFilePathByLink(const char *filename)

{

int size =

100;

char *buffer = NULL;

while(1)

{

buffer

= (char *) realloc(buffer, size);

//readlink()返回的路径名并没有以‘\0‘结尾

int nchars

= readlink(filename, buffer, size - 1);

if (nchars < 0)

{

free(buffer);

return NULL;

}

if (nchars <= size - 1)

{

buffer[nchars] = ‘\0‘;

//让路径名以‘\0‘结尾

return

buffer;

}

size *= 2;

//buffer空间不足,扩大为2倍

}

}

//通过链接文件名获取被目标文件所在目录

char* getFileDirByLink(const char

*linkfile)

{

char* pathbuf =

NULL;

pathbuf =

getFilePathByLink(linkfile);

if (NULL == pathbuf)

{

printf("getFilePathByLink() Failed!\n");

return(NULL);

}

char* last_slash = NULL;

//找到最后一个‘/‘,last_slash保存其地址

last_slash =

strrchr(pathbuf, ‘/‘);

//如果是空,则未找到‘/‘

if (last_slash == NULL)

{

printf("can not find

‘/‘!\n");

return(NULL);

}

int dir_len =

0;

char* dir = NULL;

dir_len = last_slash - pathbuf + 1;

//包括末尾的‘/‘

dir = (char*) malloc(dir_len

+ 1);

strncpy(dir, pathbuf,

dir_len);

dir[dir_len] = ‘\0‘;

return

dir;

}

int main( int argc, char * argv[]

)

{

char* myself_exec =

NULL;

myself_exec =

getFilePathByLink("/proc/self/exe");

if (NULL ==

myself_exec) {

printf("getFilePathByLink() Failed!\n");

}

else {

printf("I‘m the process,

my executable file: %s\n", myself_exec);

}

char*

myself_exec_dir = NULL;

myself_exec_dir

= getFileDirByLink("/proc/self/exe");

printf("I‘m the process, my executable file in: %s\n",

myself_exec_dir);

free(myself_exec);

free(myself_exec_dir);

return(EXIT_SUCCESS);

}

原文:http://www.cnblogs.com/cosail/p/3675423.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值