Get process name w/o using argv[0] in C function?

Chris Torek chris at mimsy.umd.edu
Sun Aug 5 00:41:59 AEST 1990


>>... I do not think I want to use a global and initialize it to argv[0]
>>in body of main(), because I do not use globals!

This is misguided zeal: not *all* globals are bad....

In article <53103 at iuvax.cs.indiana.edu> sahayman at iuvax.cs.indiana.edu
(Steve Hayman) writes:
>If you really are determined not to use a global variable for style reasons,
>you can hide the information off in another module. [example deleted]

This merely replaces the global variable with a, or in this case, two,
global functions.

So when are globals okay?  In general, if the thing being manipulated
has to last for the entire duration of the program, and the thing's
structure is dictated entirely by the goal of the program (as opposed
to some specifics of the program's implementation), then a global is
probably reasonable.  If the thing need only be known in one place, or
just a few places, then a file-scope `static' is probably best.

The real trick is finding the proper abstractions.  In this case the
goal is to print messages that include the program's name, so maybe
the best thing is to make `print a message that includes the program's
name' a function.  This replaces one global (the program's name) with
another (the function that prints messages), but in the process it
reduces the overall complexity of the whole program: instead of

	fprintf(stderr, "%s: configuration file %s not readable: %s\n",
		progname, conffile, strerror(errno));
	exit(EXIT_FAILURE);

you might have something like

	bomb_out("configuration file %s not readable: %s\n",
	    conffile, strerror(errno));

The (concrete) `print this to stderr; exit' sequence has been replaced
with the (more abstract) `stop because of this error' sequence.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris
	(New campus phone system, active sometime soon: +1 301 405 2750)



More information about the Comp.unix.questions mailing list