Get the full file name of the current executable on Unix
This C program prints the full file path to the current executable on Unix./* For printf. */ #include <stdio.h> /* For realpath. */ #include <stdlib.h> /* For PATH_MAX (the maximum length of a path). */ #include <sys/param.h> /* For strerror. */ #include <string.h> /* For errno. */ #include <errno.h> static void call_realpath (char * argv0) { char resolved_path[PATH_MAX]; if (realpath (argv0, resolved_path) == 0) { fprintf (stderr, "realpath failed: %s\n", strerror (errno)); } else { printf ("Program's full path is '%s'\n", resolved_path); } } int main (int argc, char ** argv) { printf ("Program called as '%s'\n", argv[0]); call_realpath (argv[0]); return 0; }This uses
realpath
, so it works on FreeBSD. If you are
using FreeBSD or another BSD-like operating system, you can also use
getprogname
:
/* For getprogname. */ #include <stdlib.h> #include "call_realpath.h" int main () { call_realpath (getprogname ()); return 0; }On a system like Linux, which uses glibc (the GNU C library), the value of
argv[0]
is available in a global variable
called program_invocation_name
:
#include "call_realpath.h" extern char * program_invocation_name; int main () { call_realpath (program_invocation_name); return 0; }You can also find it from reading the file
/proc/{number}/cmdline
, where {number}
is the process number, returned by getpid
.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer