Site Tools


wiki:c-exit-status

Table of Contents

C Exit status

Exit status is an integer code (0-255) returned by a program to indicate success or failure. A return value of 0 means success (EXIT_SUCCESS); any non-zero value indicates failure. The shell stores the exit status in $? for inspection with echo $?, and it can be used in shell conditionals and pipelines.

By convention, use 0 for success and 1 for generic failure; reserve other values for specific error conditions.

Example

This example demonstrates checking and using exit status in a C program and shell.

// compile: gcc -o exitstat exitstat.c
// run: ./exitstat file.txt; echo $?
// description: return and check exit status to signal program success/failure
 
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return EXIT_FAILURE;
    }
 
    FILE *f = fopen(argv[1], "r");
    if (!f) {
        perror("fopen");
        return EXIT_FAILURE;
    }
 
    char buf[256];
    while (fgets(buf, sizeof(buf), f)) {
        printf("%s", buf);
    }
 
    fclose(f);
    return EXIT_SUCCESS;
}
wiki/c-exit-status.md · Last modified: by 127.0.0.1