Eric Sosman wrote:
I was under the impression that the programme name will always be
passed as an argument so argc will be at least 1. Or is that just a
Unix
thing ?
In section 5.1.2.2.1 paragraph 2, the C Standard says
"the value of argc shall be nonnegative" (it doesn't say
"positive"), and it twice uses the phrase "if the value of
argc is greater than zero" in descriptions of the argv[]
values. The wording seems to imply the possibility that
argc might be zero in some environment that doesn't support
notions like "command line" or "program name."
The same paragraph says that if argv[0] is non-NULL it
shall point to a string that "represents the program name,"
but does not describe the form of the representation. It
also explicitly recognizes that no name might be available
even if other command-line arguments are present; in this
case, argv[0] points to an empty string "".
Other Standards that build atop the C Standard may
impose additional requirements, but I don't think I've run
across any that guarantee argv[0] will be "the" program
name. In the POSIX world, for example, argv[0] is whatever
was provided to the exec*() system call that launched the
program in the first place; this is only "conventionally"
the program name, and the convention is not enforced. (In
a few places, it is deliberately violated.)
Even when argv[0] is a program name, it doesn't follow
that you can use it to launch another copy of the program
via the system() function (or a system-specific facility).
The program "name" might turn out to be a shell alias that
isn't exported to sub-shells -- more generally, the "name"
may be "the" name only in a context that isn't available
inside the program.
The value of argv[0] is usually something that's useful
for "decorating" errors and status messages, but not "solid"
enough to rest your program's operation upon. A widely-used
hack installs a single executable file with several names,
where the program inspects argv[0] to decide how it should
behave; this sort of thing may have been justifiable in the
days of small disks and static libraries, but is hard to
defend today. Some programmers use argv[0] to find "the"
program's installation directory where configuration files
and suchlike are stored; this isn't terribly reliable (and
can be downright UNreliable on multi-user systems).