Artificial intelligent assistant

Why printf is not asyc signal safe function? We know that `printf` is not async signal safe function. And below is my basic understanding: Let's say we have called `printf` in `main` method, so the content is written to stdio buffer, just before the buffer get flushed to the file, a signal arrives and the signal handler also calls `printf`, and the second `printf` append it's content to the buffer, now the buffer has content from first call and second call, which is inconsistent, this is not correct, therefore we cannot use non asyc safe functions in signal handlers. Is my understanding correct? If my understanding is correct, then how can async safe function solve this problem? Because the safe function still need to deal with buffer, which still might contain precious call's buff data?

`printf` is non-async-signal-safe because, as you describe, it ends up manipulating global state without synchronisation. For added fun, it’s not necessarily re-entrant. In your example, the signal might be handled while the first `printf` is running, and the second `printf` could mess up the state of the first call.

The recommended async-signal-safe approach is for the signal handler to set a flag somewhere, and have the main program flow deal with the flag. This avoids issues with re-entrance, serialises output, and helps keep signal handlers speedy.

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy 4c135cc9e9eb9798a1177decca5d1ad8