Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

200 Process Environment Chapter 7


Now if we enable the 1999 ISO C compiler extensions, we see that the exit code changes:
$gcc -std=c99 hello.c enable gcc’s1999 ISO C extensions
hello.c:4: warning: return type defaults to ’int’
$./a.out
hello, world
$echo $? print the exit status
0

Note the compiler warning when we enable the 1999 ISO C extensions. This warning is
printed because the type of themainfunction is not explicitly declared to be an integer.Ifwe
were to add this declaration, the message would go away.However, if we were to enable all
recommended warnings from the compiler (with the-Wallflag), then we would see a
warning message something like ‘‘control reaches end of nonvoid function.’’

The declaration ofmainas returning an integer and the use ofexitinstead ofreturn
produces needless warnings from some compilers and thelint( 1 )program. The problem is
that these compilers don’t know that anexitfrommainis the same as areturn.One way
around these warnings, which become annoying after a while, is to usereturninstead of
exitfrommain.But doing this prevents us from using the UNIX System’sgreputility to
locate all calls toexitfrom a program. Another solution is to declaremainas returning
void,instead ofint,and continue callingexit.This gets rid of the compiler warning but
doesn’t look right (especially in a programming text), and can generate other compiler
warnings, since the return type ofmainis supposed to be a signed integer.Inthis text, we
showmainas returning an integer,since that is the definition specified by both ISO C and
POSIX.1.

Different compilers vary in the verbosity of their warnings. Note that the GNU C compiler
usually doesn’t emit these extraneous compiler warnings unless additional warning options
areused.

In the next chapter,we’ll see how any process can cause a program to be executed, wait
for the process to complete, and then fetch its exit status.

atexitFunction


With ISO C, a process can register at least 32 functions that areautomatically called by
exit.These arecalledexit handlersand areregistered by calling theatexitfunction.

#include <stdlib.h>

int atexit(void (*func)(void));

Returns: 0 if OK, nonzero on error

This declaration says that we pass the address of a function as the argument toatexit.
When this function is called, it is not passed any arguments and is not expected to
return a value. The exitfunction calls these functions in reverse order of their
registration. Each function is called as many times as it was registered.
Free download pdf