One way of looking at a computer program, is in terms of the resources it acquires, then uses to perform some useful computation.

You acquire memory, do some computations with it, then release it again.

Resource handling is so important, that it's a major task of your operating system.

You use system calls to allocate memory, create files, open file handles, write data to them, and remove files when they are no longer needed.

Many resources are cleaned up automatically when your program exits. Any memory your program allocated is released back to the operating system, and any file descriptors are closed.

Not all resources are automatically cleaned up though. Files on disk need to be unlink(2)ed before the space they occupied can be re-used.

In Linux, a file is only removed once both the reference count of file links reaches zero, when it can't be found in the file system tree any more, and no processes have open file handles to it.

Terminating your processes are not the only way to close open file handles though, as there is a limit to the number of file handles a process can have open.

For this reason, the close(2) system call exists, so when you no longer need a file to be open, you can close it.

Because of this, programs are generally structured around the acquisition of resources, operating on them, then releasing them again.

For example, in shell scripts you often need to allocate temporary files and directories. These are not automatically cleaned up when your process exits, so you need cleanup code. The trap shell builtin is the most useful tool available.

td="$(mktemp -d")
trap 'rm -rf "$td"' 0 # remove tempdir on exit
cd "$td"
…

Trap is limited to being given a command to run on a signal, which falls apart quickly when you have multiple resources to handle. At this point you should probably be using a more full-featured programming language.

Subsequent articles will cover appropriate resource cleanup idioms in other programming languages.