Is argv[0] Guaranteed to Be the Executable Name?
When working with C or C applications, it is often assumed that the first argument passed to main() (argv[0]) represents the name of the executable. However, this assumption may not always hold true.
The Standard's Definition
According to the ISO C11 standard:
"If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv0 shall be the null character if the program name is not available from the host environment."
This statement clarifies that argv[0] should only contain the program name if the name is available from the host environment. Moreover, it may not be an exact match, but rather a representation.
Implementation-Defined Values
The standard further states that the values in argv[0] are implementation-defined. This means that different operating systems or environments may handle the population of argv[0] differently.
For instance, on UNIX-based systems, exec family calls can assign arbitrary values to argv[0]. However, the standard requires that the implementation documents this behavior.
Conclusion
Therefore, while it is a common convention for argv[0] to contain the executable name, this is not guaranteed by the C or C standards. The implementation may vary the contents of argv[0] as long as it documents its behavior.
The above is the detailed content of Is argv[0] Always the Executable Name in C/C ?. For more information, please follow other related articles on the PHP Chinese website!