Search code examples
clinuxgccexitatexit

Better replacement for exit(), atexit() in C


I am new to C programming. I used to think using exit() was the cleanest way of process termination (as it is capable of removing temporary files, closing open files, normal process termination...), but when I tried man exit command on the terminal (Ubuntu 16.04.5, gcc 5.4.0) I saw the following line:

The exit() function uses a global variable that is not protected, so it is not thread-safe.

After that I tried to make some research about better replacement for exit() (to change my programming behavior from the beginning). While doing that I faced with this question in which side effects of exit() is mentioned and it is suggested to use atexit() properly to solve the problem (at least partially).

There were some cases in which using abort() was preferred over exit(). On top of that, this question suggests that atexit() might also be harmful.

So here are my questions:

  • Is there any general and better way of process terminating (which is guaranteed to clean like exit() and is not harmful for the system at any case)?
  • If the answer to the first question is NO!, what is the best possible way of process terminating (including the cases in which they are most useful)?

Solution

  • what is the best possible way of process terminating

    1. If going single threaded just use exit(), as your code is not going multi-threaded.
    2. Else make sure all but one thread have ended before the last thread and then safely call exit() because of 1. above.