Skip to main content

Program Exit Status

Program Exit Status

  • In C, the exit status is a value returned by a program to the operating system or calling process to indicate the termination status.

  • It is a way to communicate the outcome of a program's execution to its parent process or the system.

  • The exit() function in C is used to terminate a program and specify its exit status. It takes an integer argument that represents the exit status code.

  • Conventionally, an exit status of 0 indicates successful execution, while any non-zero value indicates an error or abnormal termination.

Example

Here's an example of using exit() to handle errors in C:

#include <stdio.h>
#include <stdlib.h>

int main() {
int dividend = 10;
int divisor = 0;

if (divisor == 0) {
printf("Error: Divide by zero is not allowed.\n");
exit(1); // Exit with a non-zero status code indicating an error
}

int result = dividend / divisor;
printf("Result: %d\n", result);

return 0;
}

Explanation:

  • If the divisor is 0, the program detects the error, prints an error message, and then calls exit(1) to terminate the program with an exit status of 1, indicating an error condition.
  • The value 1 is a convention, and you can choose other non-zero values to represent different types of errors.

In the calling process or the shell that executed the program, you can access the exit status code using various means.

For example: in a Unix-like shell, you can access the exit status using the $? variable. The value of $? will be the exit status of the last executed program.

$ gcc error_handling.c -o error_handling
$ ./error_handling
Error: Divide by zero is not allowed.
$ echo $?
1
exit status
  • By using the exit status code, you can indicate whether your program executed successfully or encountered errors.
  • This allows you to handle different scenarios or perform appropriate actions based on the exit status when invoking your program from another process or shell script.