Jan
5

How can I get what my main function has returned in Linux?

 

In a C program if we want to give some input from terminal then we can give it by:

int main(int argc, char *argv[])

In the same way, if we want to get return value of main() function then how can we get it?

 

In each main() we write return 1 or return 0; how can we know what my main() has returned at terminal?

#include<stdio.h>
int main()
{
printf("Share Programing Tips");
return 32;
}

Now save this program as test.c file and in terminal run following command

$ gcc test.c
 
$ ./a.out
 
$ echo $?  // this will show the return value of main

Most shells store the exit code of the previous run command in $? so you can store or display it.

A C program always has an exit code, which the program may decide for itself if it terminates normally, by returning a value from the main function or by calling the exit function. If the program terminates abnormally, for example by a segmentation fault, the operating system decides the exit code.

In Unix (Posix), the exit code is an 8-bit value: 0-255. It is combined with some other metadata to a status: the other metadata includes information about whether the program terminated normally or not, if it was terminated because of a signal, and if so, which signal. For details, see the wait(2) manual page.

In Unix, at the shell, the status of the previous command is accessible as the $? special variable. Because the exit code is only 8 bits, and it’s treated as an unsigned integer, if you return a negative value, it gets turned into a positive one: -1 becomes 255. Likewise, if you return a value greater than 255 only the least significant 8 bits are used: 256 becomes 0.

You can use this return code in linux script file.

 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link