glibc function to retrieve current executable name?

后端 未结 2 1116
执念已碎
执念已碎 2020-12-29 09:58

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

2条回答
  •  不思量自难忘°
    2020-12-29 10:26

    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 
    #include 
    #include 
    #include 
    
    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().

提交回复
热议问题