且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

glibc函数检索当前的可执行文件名称?

更新时间:2022-10-23 20:45:14

标准C和glibc,你有argv [0]:

pre $ int c main int $ b

argv 数组的第一个元素是程序名称。



然而,单独确定可执行文件的位置并不够。参数实际上是由运行程序的程序设置的 - 无论是shell还是窗口管理器 - 它们都不是非常有用。如果您的程序位于路径中,并且只需在bash shell中使用

your_program



运行该程序,那么your_program就是您将在argv [0]中获得的所有内容。



对于完整的可执行文件路径,linux有 / proc 文件系统。在 / proc 下,每个正在运行的进程都会获得自己的目录,并以其进程ID命名。正在运行的进程还可以在 / proc / self 下看到自己的子树。每个进程获得的文件之一是 / proc / [pid] / exe ,它是运行进程的实际可执行文件的符号链接。



所以你可以得到像这样的完整的可执行路径:

  #include< stdio.h中&GT; 
#include< stdlib.h>
#include< sys / types.h>
#include< unistd.h>

int main(void){
char exe [1024];
int ret;

ret = readlink(/ proc / self / exe,exe,sizeof(exe)-1);
if(ret == - 1){
fprintf(stderr,ERRORRRRR \\\
);
exit(1);
}
exe [ret] = 0;
printf(我是%s \\\
,exe);
}

您也可以将 / proc / [pid] / exe 直接转换为 addr2line()


i'm wondering if there is a glibc function that i can use from gcc/g++ that will retrieve the current executable.

The purpose of this is to provide the -e argument to addr2line as shown in this answer

In standard C and glibc, you have argv[0]:

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

the first element of the argv array is the program name.

However it's not necessarily enough on its own to determine where exactly the executable is. The argument is actually set by the program that ran your program - be it a shell or a window manager - and they aren't terribly helpful. If your program is in the path and you run the program simply with

your_program

at a bash shell, then "your_program" is all you will get in argv[0].

For the full executable path, linux has the /proc filesystem. Under /proc each running process gets its own "directory", named by its process id. The running process can also see its own subtree under /proc/self. One of the files that each process gets is /proc/[pid]/exe, which is a symbolic link to the actual executable the process is running.

So you can get the actual full executable path like this:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    char exe[1024];
    int ret;

    ret = readlink("/proc/self/exe",exe,sizeof(exe)-1);
    if(ret ==-1) {
        fprintf(stderr,"ERRORRRRR\n");
        exit(1);
    }
    exe[ret] = 0;
    printf("I am %s\n",exe);
}

You may also be able to pass /proc/[pid]/exe directly to addr2line().