Method 1
Use extern char *__progname
introduce:
__progname is a special global variable defined in the C standard library, holding the name of the currently running program. It is only available in Unix-like systems, such as: Linux, MacOS.
Analysis:
The meaning of extern: is to declare that this variable is defined elsewhere, usually in C runtime.
char *__progname: represents a pointer to a character array, the value contains the name of the running executable file
The value of __progname: is usually not the full path of the file, and only contains the name of the file. For example: /usr/bin/myapp, then __progname is myapp
Example of usage:
#include <> extern char *__progname; int main(void) { printf("This program is called: %s\n", __progname); return 0; }
Method 2
Use argv[0] to get
introduce:
This is a common way to get the program name, and it can be used in both Unix-like systems and Windows-like systems.
Analysis:
If you only focus on Unix-like platforms and are incompatible with expansion platforms, it is more convenient to use __progname directly. argv[0] needs to explicitly specify parameters in the method.
Example of usage:
#include <> int main(int argc, char *argv[]) { printf("Program name: %s\n", argv[0]); return 0; }
Method 3
Use /proc/self/exe to get
introduce:
This method can only be used in Linux systems. The execution path of the program is obtained by reading the soft link /proc/self/exe.
Analysis:
/proc/self/exe is a soft link to the executable file of the current process.
proc involves virtual file system (provides process and system information)
self is actually a PID pointing to the currently running process. For example, the current PID is: 1234, then /proc/1234/exe is equal to /proc/self/exe.
Example of usage:
#include <> #include <> int main() { char path[1024]; ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1); if (len != -1) { path[len] = '\0'; // Null-terminate the string printf("Executable path: %s\n", path); } else { perror("readlink"); } return 0; }
Method 4
Get it using GetModuleFileName API
introduce:
This method can only be used in Windows systems.
Analysis:
GetModuleFileName can get the full path to the executable file
Example of usage:
#include <> #include <> int main() { char path[MAX_PATH]; GetModuleFileName(NULL, path, MAX_PATH); printf("Program path: %s\n", path); return 0; }
Extra
How to download and get the source code of C runtime
Download using package manager, such as in Debian/Ubuntu system
sudo apt-get source libc6
Download the compressed package from the official website
/software/libc/
Download from Github image repository
git clone /bminor/
This is the end of this article about four methods to obtain program names in C language. For more related contents in C language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!