Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

where does main() function in C program return in linux ?

Status
Not open for further replies.

iaindian

Programmer
Jun 10, 2002
2
0
0
US
Can any one tell me where does the return value of main ()in C program go ?

eg:

int main()
{
return 0;
}


In the above program where does this return value "0" go when you execute the executable (in unix ) ?
 
It goes to the invoking program (can be anything, another program, the shell - which is a program, etc).

Usually (not necessarly), programs return -1 if there were problems in their execution so the calling program can check upon their status at least through this indicator. [red]Nosferatu[/red]
We are what we eat...
There's no such thing as free meal...
once stated: methane@personal.ro
 
After running a C executable, the value returned by main is available to the parent process (the one who launched the executable).
If the parent is a shell, the returned value is stored in the shell variable $? (or $status for csh).
Unix standard practice is to return 0 for no problem and non zero for problems (look for 'EXIT STATUS' in any unix utility man page e.g. 'man grep').

Note that usable values range from 0 to 256 (or 128 ?) because unix store this value in one byte. A value greater than 256 means the program was killed by a signal.

So you can do the following in a shell script:
Code:
myCExec arg1 arg2
if [ $? -ne 0 ]; then
    echo "program failed: exiting"
    exit 1
fi

echo "No problem: keep going"
...

A more compact syntax:
Code:
if myCExec arg1 arg2; then
   echo "No problem: keep going"
else
   echo "Program failed: exiting"
   exit 1;
fi

...
 
Anjanku,
I would say that you should be a little bit carefull about the return values of sytem calls in Linux. Linux is currently not compliant with the standards and its errno policy is quite different from traditional UNIXes.
The best way is to read the man pages. And yeah echo $? will give you the return value of a program invoked on the command line.

cheers

amit
crazy_indian@lycos.com

to bug is human to debug devine
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top