Question:
Is it possible to execute code even after the program exits the main() function?
Answer:
The standard C library provides a function named atexit() that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the atexit() function. Source: CoolInterview.com
it is not at all possible to execute the code after exit the main.
Source: CoolInterview.com
Answered by: sreelatha | Date:
| Contact sreelatha
Yes, It is possible execute code even after the program exits the main() function. Explanation :- We can crate Child Process(Thread)and make the child process to sleep and by that time, we can make the Main thread to finish its execution and exit. ( In C main() act as the Main Thread ).After the main thread exits, the child thread can run after coming from sleep state. Source: CoolInterview.com
Answered by: Utkal | Date:
| Contact Utkal
the atexit() function is called before exiting the main() function and it is not at all possible to carry on execution after exiting the main() function. Source: CoolInterview.com
Answered by: Nilotpal | Date:
| Contact Nilotpal
Using atexit() we can execute code even after exit from main program.
I think the following program will help in understanding the concept.
Here, I am initializing the function that has to be executed after exit of the main program, printing some output and calling the return, which exits the function. Later i am printing some more lines of code (which i am sure that wont be called as the function is exited). Once the function exits, it will call the funcion which is initialized using atexit().
#include<stdio.h>
void myFunction_Onexit() { printf(" Welcome to user exit function.
Here u can do anything "); system("pause"); } int main() { printf(" In main function before return "); atexit(myFunction_Onexit); system("pause"); return 0; printf(" In main function after return "); system("pause"); return 0; } Source: CoolInterview.com
Answered by: Syed Baseer Ahmed | Date: 12/5/2007
| Contact Syed Baseer Ahmed
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|