What is the difference between returning from main with some exit code and calling exit giving the exit code as parameter ?
Basically the difference between following programs !
well, there are three ways for the processes to exit: –
1. Voluntary exit (implicit)
2. Voluntary exit (explicit)
3. Involunatary exit
Voluntary exit can be implicit e.g. in case of return and explicit e.g.
in case of a call to exit(). Involuntary exit is like being killed by a
third process, receiving a SIGSTP signal (or other signals whose default ot set
behavior results in terminating the process).
+ ‘return’ is an implicit voluntary termination of process
+ ‘exit’ is an explicit voluntary termination.
Note: both calls actually execute code in the function ‘do_exit’ ultimately.
I also tried writing above programs and inspecting the assembly just to know if
there is any difference in the code ultimately. Here are they:
[ used ‘objdump -d’ function and showing here only the function ‘main’ disassembly]
//ret.o – main
80482f4: 55 push %ebp
80482f5: 89 e5 mov %esp,%ebp
80482f7: 83 ec 08 sub $0x8,%esp
80482fa: 83 e4 f0 and $0xfffffff0,%esp
80482fd: b8 00 00 00 00 mov $0x0,%eax
8048302: 29 c4 sub %eax,%esp
8048304: b8 2b 00 00 00 mov $0x2b,%eax
8048309: c9 leave
804830a: c3 ret
804830b: 90 nop
//exit.o – main
8048324: 55 push %ebp
8048325: 89 e5 mov %esp,%ebp
8048327: 83 ec 08 sub $0x8,%esp
804832a: 83 e4 f0 and $0xfffffff0,%esp
804832d: b8 00 00 00 00 mov $0x0,%eax
8048332: 29 c4 sub %eax,%esp
8048334: 83 ec 0c sub $0xc,%esp
8048337: 6a 2b push $0x2b
8048339: e8 26 ff ff ff call 8048264
804833e: 90 nop
804833f: 90 nop
So there is some difference and looking closely it is that in case of ‘exit’
and explicit ‘call’ is made using call instruction (and hence pushing of
arguments to the stack) while this overhead is avoided in case of a return.
Ok. so that was a short dip in the code for two empty programs – result of a free mind.