Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Happens when main() function does not return zero

Please consider the following Code:

#include <stdio.h>

int main()
{
    int x;
    printf ("\nEnter x: ");
    scanf ("%d", &x);

    return x;
}

Output:
$Enter x: -2

$echo $?
254

My Question is:

The OS knows that return value of main() by executing a process P (The above code under execution) is NON-ZERO.

Does the OS does any kind of Handling in such cases?

like image 591
Sandeep Singh Avatar asked Jan 15 '23 02:01

Sandeep Singh


2 Answers

It has to be made clear what you are understanding by the "operating system" here.

If you look from the shell's point of view (which usually is just another userspace program anyway, and not a part of the kernel itself), the exit value of a process is used to evaluate the value of an expression and is important when doing shell programming as it is the most natural check one does after the termination of a process.

From the point of view of the kernel, the exit value of a process is largely dismissed. The kernel has to clean after the process regardless of the exit code it has returned.

like image 154
Blagovest Buyukliev Avatar answered Jan 17 '23 17:01

Blagovest Buyukliev


The return value actually indicates the status of program completion. A non-zero value indicates the program has been terminated abnormally. The status may be used by used by other programs, so it is always a good practice to return the actual status.

like image 37
Sakthi Kumar Avatar answered Jan 17 '23 17:01

Sakthi Kumar