Use cleanup handlers to restore conditions to a state that is consistent with that state at the point of origin. This consistent state includes cleaning up allocated resources and restoring invariants. Use the pthread_cleanup_push(3C) and pthread_cleanup_pop(3C) functions to manage the handlers.
Cleanup handlers are pushed and popped in the same lexical scope of a program. The push and pop should always match. Otherwise, compiler errors are generated.
Use pthread_cleanup_push(3C) to push a cleanup handler onto a cleanup stack (LIFO).
void pthread_cleanup_push(void(*routine)(void *), void *args);
#include <pthread.h> /* push the handler "routine" on cleanup stack */ pthread_cleanup_push (routine, arg);
pthread_cleanup_push() has no return value.