Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Doing something when the program exits

Tags:

c

exit

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.

like image 654
Frank Vilea Avatar asked May 21 '11 14:05

Frank Vilea


People also ask

Is there an exit function in C?

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.

Which function is used to exit from 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.

What is exit code in C?

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.

How do you end C program statement?

So the C family has three ways to end the program: exit(), return, and final closing brace.


2 Answers

look into the atexit API of the C standard library.

like image 108
Constantinius Avatar answered Sep 24 '22 16:09

Constantinius


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.

like image 27
R.. GitHub STOP HELPING ICE Avatar answered Sep 21 '22 16:09

R.. GitHub STOP HELPING ICE