BЈовић BЈовић - 4 months ago 7
Linux Question

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

I know the program name is passed as the first argument, and next simple example will print it to the standard output :

#include <iostream>
int main ( int argc, char *argv[] )
{
std::cout<<argv[0]<<std::endl;
}


Is there a function to get the program name?

EDIT

I am starting the program from the shell, and the above code will always print the program name (I am using fedora 9, but I am sure it works in other distros).

I have found that /proc/self/ directory might contain what I am looking for, but I couldn't find what exactly in that directory.

Answer

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.)