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.
问题:
回答1:
look into the atexit
API of the C standard library.
回答2:
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.
回答3:
If your application terminates normally, it'll run functions registered through atexit
. This is a standard function, available on Windows, unix and every other platform, and also in C++.
Note that “terminates normally” means through calls to exit()
or by returning from main()
. If your application terminates via abort()
or _exit()
, or if it is killed summarily from the outside, it may not have the opportunity to do any cleanup. There may be a better approach, possibly setting and clearing the flag in a wrapper program that does the cleanup regardless of how your program terminates, or dispensing with this flag altogether.
回答4:
There are better ways of preventing the application to run twice. One solution is to use named mutexes that are system wide. Another and maybe simpler solution is to lock a file (open for writing). Even when the application crashes resources are freed by the OS and you will be able to start the application again, because the file or mutex will not be locked anymore.