How to make a function async-signal-safe?

You can use fcntl() as an alternative to flock().


flock() is generally async-signal-safe because it is a system call. Its semantics make it hard to implement it differently. It is not in POSIX's list of async-signal-safe functions because it is not in POSIX at all.

You likely do not need the explicit unlock because flock() locks are released automatically when all file descriptors referring to the open file description are closed.

The printf() and fprintf() calls should be replaced with appropriate write() calls. The stdio functions are not in the list of async-signal-safe functions and are often strongly async-signal-unsafe.

The abort() call is probably best replaced by setting the signal to the default action and resending it to self; this way, shells know that your program exited because of the signal and can abort command sequences when appropriate.