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.
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 ofargv[0]
inmain()
, with the difference that the scope ofprogram_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 asprogram_invocation_name
, with all text up to and including the final slash (/), if any, removed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With