LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Programs · Question 8

Clean shutdown with atexit and exit in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Register two cleanup handlers with atexit, process a list of jobs, and stop the program with exit() from inside a helper when a job is invalid.

Solution
main.c
#include <stdio.h>
#include <stdlib.h>

static int processed = 0;

static void report(void) { printf("processed %d job(s)\n", processed); }
static void release(void) { printf("resources released\n"); }

static void run_job(int id) {
    if (id < 0) {
        printf("invalid job %d, stopping\n", id);
        exit(EXIT_SUCCESS);      /* a real program would use EXIT_FAILURE */
    }
    printf("job %d done\n", id);
    processed++;
}

int main(void) {
    atexit(release);
    atexit(report);              /* runs first */
    int jobs[] = {101, 102, -7, 104};
    for (int i = 0; i < 4; i++)
        run_job(jobs[i]);
    printf("all jobs finished\n");
    return 0;
}

Output Verified by compiling and running

job 101 done
job 102 done
invalid job -7, stopping
processed 2 job(s)
resources released

exit can be called from anywhere and still performs an orderly shutdown: the atexit handlers run (last registered first) and output is flushed. Job 104 is never processed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links