您的位置:首页 > 运维架构 > Linux

Linux中获取当前程序路径的方法

2012-05-22 13:37 483 查看
1、命令行实现:转自:http://www.linuxdiyf.com/viewarticle.php?id=84177

#!/bin/sh

cur_dir=$(pwd)

echo $cur_dir

注意:在cur_dir后没空格,=后面也不能有空格,不然它会认为空格不是路径而报错



2、程序实现:转自:http://topic.csdn.net/u/20071217/13/78e81ffa-b30c-4685-a58a-2eb5e181b825.html

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

#include <stdio.h>

int getpath(char *buf)

{

long size;

char *ptr;

size = pathconf(".",_PC_PATH_MAX);

if((ptr = (char*)malloc((size_t)size)) != NULL)

{

memset(ptr,0,size);

sprintf(ptr,"/proc/%d/exe",getpid());

}

else

return -1;

return readlink(ptr,buf,size);

}

int main()

{

char buf[128];

getpath(buf);

printf("%s\n",buf);

}



转自:http://hi.baidu.com/jrckkyy/blog/item/6f74ebee3b4768e3b3fb9542.html

http://hi.baidu.com/xlt1888/blog/item/0958fd86668b73cc9123d99f.html



#include <unistd.h>

#include <stdio.h>

int main(int argc , char* argv[])

{

char buf[1024] = { 0 };

int n=0;

n =readlink("/proc/self/exe" , buf , sizeof(buf));

if( n > 0 && n < (int)sizeof(buf))

{

Buf
= ‘\0’;

printf("%s\n", buf);

}

}



还可以利用getcwd函数来实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: