In C, if my application ends unexpectedly can I call a function before that happens? I'm writing a flag into a database (processRunning = 1) that prevents other applications from starting a similar process. When the application ends it would not change that flag back.
The exit() function in C. The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.
exit(): When a user wants to exit a program from this function is used. It is a void return type function that calls all functions registered at the exit and terminates the program.
The purpose of the exit() function is to terminate the execution of a program. The “return 0”(or EXIT_SUCCESS) implies that the code has executed successfully without any error. Exit codes other than “0”(or EXIT_FAILURE) indicate the presence of an error in the code.
So the C family has three ways to end the program: exit(), return, and final closing brace.
look into the atexit
API of the C standard library.
On POSIX, the proper solution is to protect the data with a robust mutex in shared memory. If your process has died with a robust mutex held, another program trying to lock the mutex will not deadlock but will instead return EOWNERDEAD
, and then it has the opportunity to clean up the state protected by the mutex and call pthread_mutex_consistent
.
Edit: If your only want to prevent multiple instances of the program from running, there are surely better/simpler ways, like holding a lock on the database file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With