Linux程序消除相对文件路径的影响


Linux程序通常会有配置文件,如果配置文件采用了相对路径,例如:"../src/config.xml"

那么在当前路径下,执行没有问题;
如果换到其他路径,执行就出现问题,找不到该文件;
在编写脚本的时候,就必须首先cd 到执行文件所在路径,然后再执行;

如果要消除这个影响,又不能写死了路径,那么就需要将相对路径,变换为绝对路径;
步骤:
1. 首先,取得程序所在的路径;
2. 加上相对路径,那么就取得绝对路径;
请注意:不是当前路径,getcwd可以取得当前路径;而不是程序的绝对路径;我当时犯过这个错误!

下面介绍,取得程序所在的路径的方法:
方法1. 如果不在意可能安全隐患,可以使用procfs,然后readlink,把当前进程的pid对应的目录下面的file指向的位置读出来(注意需要先挂载procfs)  
pit_t   mypid   =   getpid();  
sprintf(strsrc,   "/proc/%d/file",   mypid);  
readlink(strsrc,   strdest,   LEN);//LEN最好是你的_POSIX_PATH_MAX

方法2. 使用realpath函数,然后dirname;最后拼接出配置文件绝对路径;

char path[PATH_MAX];
char *rpath = realpath(argv[0], path);
LOG_IT(LOG_MAIN, LOG_DEBUG, "argv[0]: %s, realpath %s", argv[0], rpath);

char* base = basename(path);
char* dir = dirname(path);
LOG_IT(LOG_MAIN, LOG_DEBUG, "base: %s, dir %s", base, dir);

char conf_file[2048];
int maxlen_conf = 2048;
snprintf(conf_file, maxlen_conf, "%s/%s", dir, "../src/config.xml");
LOG_IT(LOG_MAIN, LOG_DEBUG, "conf_file %s", conf_file);

相关内容