Use cleanup handlers to restore conditions to a state consistent with that at the point of origin, such as cleaning up allocated resources and restoring invariants. Use the pthread_cleanup_push(3T) and pthread_cleanup_pop(3T) functions to manage the handlers.
Cleanup handlers are pushed and popped in the same lexical scope of a program. They should always match; otherwise compiler errors will be generated.
Use pthread_cleanup_push(3T) to push a cleanup handler onto a cleanup stack (LIFO).
Prototype: void pthread_cleanup_push(void(*routine)(void *), void *args);
#include <pthread.h> /* push the handler "routine" on cleanup stack */ pthread_cleanup_push (routine, arg);