Without access to argv[0], how do I get the program name? Without access to argv[0], how do I get the program name? linux linux

Without access to argv[0], how do I get the program name?


No, there is no such function. Linux stores the program name in __progname, but that's not a public interface. In case you want to use this for warnings/error messages, use the err(3) functions.

If you want the full path of the running program, call readlink on /proc/self/exe:

char *program_path(){    char *path = malloc(PATH_MAX);    if (path != NULL) {        if (readlink("/proc/self/exe", path, PATH_MAX) == -1) {            free(path);            path = NULL;        }    }    return path;}

(I believe __progname is set to the basename of argv[0]. Check out the glibc sources to be sure.)


This is not guaranteed.

Usually, argv[0] holds the executable name but one can call your executable using execve and set it to something else.

In a word: don't rely on this.


GLIBC-specific solution:

#include <errno.h>...fprintf(stderr, "Program name is %s\n", program_invocation_name);

From man invocation_name:

program_invocation_name contains the name that was used to invoke the calling program. This is the same as the value of argv[0] in main(), with the difference that the scope of program_invocation_name is global.

program_invocation_short_name contains the basename component of name that was used to invoke the calling program. That is, it is the same value as program_invocation_name, with all text up to and including the final slash (/), if any, removed.