在Linux中获取当前程序运行的绝对路径

xiaoxiao2021-02-28  7

readlink() 函数可以获取一个符号链接的路径,而在Linux中的 /proc/self/exe 符号链接为当前运行程序,所以可以利用它获取当前运行程序的绝对路径,代码如下

#include <stdio.h> #include <unistd.h> #include <string.h> size_t get_executable_path( char* processdir,char* processname, size_t len) { char* path_end; if(readlink("/proc/self/exe", processdir,len) <=0) { return -1; } printf("get current path is :%s\n", processdir); path_end = strrchr(processdir, '/'); if(path_end == NULL) { return -1; } ++path_end; strcpy(processname, path_end); *path_end = '\0'; return (size_t)(path_end - processdir); } int main(void) { char binpath[256]; char process[256]; get_executable_path(binpath, process, sizeof(binpath)); printf("---------->>> current path is : %s\n", binpath); printf("---------->>> current process is : %s\n", process); return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-2400126.html

最新回复(0)