glibc函数检索当前的可执行文件名称? [英] glibc function to retrieve current executable name?

查看:191
本文介绍了glibc函数检索当前的可执行文件名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可以从gcc / g ++中使用的glibc函数来检索当前的可执行文件。

这样做的目的是提供如 addr2line 的-e参数 - 从程序到打印 - 它的堆栈跟踪/ 4611112#4611112>这个答案

解决方案

标准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中> 
#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().

这篇关于glibc函数检索当前的可执行文件名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆