In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.orgwrote:
><OT>
In a typical shell (at least the kind I'm used to under Unix), a
program invocation is very different from a function call. The entity
that actually calls the main() function is not something that's even
visible to a shell, shell script. or user program.
</OT>
More OT...
Typically, an exectable program file will have something in it that
identifies the address at which the OS should start running it, or
else the OS will start it at some fixed address. The program that
creates the executable - the compiler or more likely linker - will
have placed a function at that address which does any necessary setup
(dynamic linking for example) and then calls main(). So when main()
returns, it will return to that function. That function will then
call exit(), which does things like closing open files and running
atexit() functions. The parameter passed to exit() is the value
returned by main(). exit() then terminates the program.
How does exit() return the value to the shell (or other parent
program)? Many (perhaps most) operating systems don't have any
concept of a program just "coming to its end". It can't just run out
of code, or return in the normal way. If it runs off the end of its
memory, it will get a signal (e.g. segmentation violation) and the OS
will terminate it. Something similar is likely to happen if it
executes a return instruction from the initial function - there won't
be a useful addess on the stack for it to return to. Instead exit()
does a system call to tell the OS to terminate it, and it provides its
argument - the value returned from main() - as an argument to that
system call. The OS notes this value, and terminates the program.
Meanwhile, the parent process - such as the shell - has probably
called a system call that means "wait for my child process to finish".
That system call now returns with a value corresponding to that
returned by main() in the child.
-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.