Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using '__progname' instead of argv[0]

Tags:

c

unix

In the C / Unix environment I work in, I see some developers using __progname instead of argv[0] for usage messages. Is there some advantage to this? What's the difference between __progname and argv[0]. Is it portable?

like image 403
Leonard Avatar asked Nov 07 '08 21:11

Leonard


3 Answers

__progname isn't standard and therefore not portable, prefer argv[0]. I suppose __progname could lookup a string resource to get the name which isn't dependent on the filename you ran it as. But argv[0] will give you the name they actually ran it as which I would find more useful.

like image 98
Evan Teran Avatar answered Nov 02 '22 06:11

Evan Teran


Using __progname allows you to alter the contents of the argv[] array while still maintaining the program name. Some of the common tools such as getopt() modify argv[] as they process the arguments.

For portability, you can strcopy argv[0] into your own progname buffer when your program starts.

like image 34
Adam Liss Avatar answered Nov 02 '22 06:11

Adam Liss


I see at least two potential problems with argv[0].

First, argv[0] or argv itself may be NULL if execve() caller was evil or careless enough. Calling execve("foobar", NULL, NULL) is usually an easy and fun way to prove an over confident programmer his code is not sig11-proof.

It must also be noted that argv will not be defined outside of main() while __progname is usually defined as a global variable you can use from within your usage() function or even before main() is called (like non standard GCC constructors).

like image 37
Krunch Avatar answered Nov 02 '22 05:11

Krunch