CodeBlanks Logo Icon CodeBlanks

Automatic cleanup

Learn automatic lock cleanup and safety.

Automatic cleanup

Automatic lock cleanup improves safety. For flock, calling close(fd) releases the lock immediately; the same holds for fcntl. So calling close early prevents lock leakage.

If the program terminates unexpectedly, the kernel closes all descriptors and releases locks. Still, registering a cleanup function with atexit(cleanup) is a good habit. This function does close, unlink and other cleanup. So whether the program exits normally or with error, no resources leak.

Exit cleanup with atexit

atexit is declared in <stdlib.h>. When the program exits normally, it calls the registered functions. You define a function with signature void cleanup(void) and register it with atexit(cleanup).

For testing, a simple scenario: open a file, take flock(fd, LOCK_EX), print printf("locked\n"), release the lock with close(fd), print printf("cleaned\n"). atexit is not strictly needed here; but in real apps, when the program returns or exits anywhere, the cleanup function runs.

Practice Demonstrate automatic cleanup

Open the file with int fd = open("/tmp/cb_clean.txt", O_CREAT | O_RDWR, 0644);. Call flock(fd, LOCK_EX); and printf("locked\n");. Release the lock automatically with close(fd);. Print printf("cleaned\n");. Call unlink("/tmp/cb_clean.txt");.

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

// Open file and take lock
// Release the lock with close
// Print cleaned and remove file

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

int main(void) {
    int fd = open("/tmp/cb_clean.txt", O_CREAT | O_RDWR, 0644);
    flock(fd, LOCK_EX);
    printf("locked\n");
    close(fd);
    printf("cleaned\n");
    unlink("/tmp/cb_clean.txt");
    return 0;
}

Expected output

locked
cleaned

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match cleanup mechanisms

Term Meaning
close Releases lock
atexit Exit function
unlink Removes file
kernel Cleans on crash

2 What does close(fd) do to a flock lock?

  • Releases it Correct answer
  • Makes it permanent
  • Nothing
  • Duplicates it

Explanation: close(fd) releases the flock lock automatically.

3 atexit call

Question
atexit(____);
Answer
atexit(cleanup);

Explanation: atexit runs cleanup at exit.

All lessons in Advanced