Course contentsShow
← C
Lesson 1072 of 1,21915. Systems ProgrammingFree lesson

Process termination and exit codes

Process termination and exit codes

What you'll learn: How a process signals success or failure to the operating system using return values.

The Final Report

Every time a C program finishes, it doesn't just vanish; it leaves behind a "status report" for the operating system. Think of a process like a specialized contractor you hired to do a job. When the contractor finishes, they don't just walk away—they give you a thumbs-up (everything went great) or a specific error code (the pipe leaked, or the parts were missing).

In C, this status report is an integer known as the exit code.

Returning from Main

You have likely been writing return 0; at the end of your main() functions since day one. By doing this, you are actually communicating with the parent process (usually the terminal or the OS).

In the world of systems programming:

  • 0 typically means Success. The task was completed without issues.
  • Any non-zero value (1 to 255) means Failure. Different numbers can represent different types of errors.

Code Example: Success vs. Failure

Here is how a program might decide how to terminate based on whether it successfully "did its job."

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

int main(int argc, char *argv[]) {
    // Imagine our program requires an argument to work
    if (argc < 2) {
        printf("Error: No input provided.\n");
        // Exit with a failure code (1)
        return 1; 
    }

    printf("Processing: %s\n", argv[1]);
    
    // Exit with a success code (0)
    return 0;
}

Why It Matters

Systems programming is about building tools that work together. If you write a script that runs ten different C programs in a row, that script needs to know if the first program failed so it can stop before causing damage.

When you run a command in a Linux terminal, you can actually check the exit code of the last program by typing echo $?. If your C program returned 0, you'll see 0. If it returned 1, you'll see 1. This simple integer is the fundamental way processes talk to each other about their results.

Key takeaway

An exit code of 0 means success, while any non-zero value signals an error to the operating system.