Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 382
BЈовић Avatar asked Oct 27 '10 09:10

BЈовић


3 Answers

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.

like image 193
Sauron Avatar answered Nov 20 '22 14:11

Sauron


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

like image 24
Fred Foo Avatar answered Nov 20 '22 16:11

Fred Foo


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.

like image 9
ereOn Avatar answered Nov 20 '22 15:11

ereOn