Sunday, September 14, 2014

Unix Prog: Exit Process -- exit

1. System Definition

 ubuntu@ip-172-31-23-227:~$ less /usr/include/stdlib.h  
 ......  
 /* Call all functions registered with `atexit' and `on_exit',  
   in the reverse of the order in which they were registered,  
   perform stdio cleanup, and terminate program execution with STATUS. */  
 extern void exit (int __status) __THROW __attribute__ ((__noreturn__));  
 ......  
 /* Terminate the program with STATUS without calling any of the  
   functions registered with `atexit' or `on_exit'. */  
 extern void _Exit (int __status) __THROW __attribute__ ((__noreturn__));  
 ......  
 ubuntu@ip-172-31-23-227:~$ less /usr/include/unistd.h  
 ......  
 /* Terminate program execution with the low-order 8 bits of STATUS. */  
 extern void _exit (int __status) __attribute__ ((__noreturn__));  
 ......  

2. 5 normal ways to exit process
1) return from main function. This is equivalent to "exit".
2) Call the exit function, as described above.
3) Call the _Exit or _exit function
4) Call the return from the start routine of last thread in the process, the return value of the thread is not taken as process's return value.
5) Call the pthread_exit function from the last thread in the process.

3. 3 Abnormal ways to exit function
1) Call abort, generating the SIGABRT signal
2) When the process receive signal generated by itself or other process
3) The last thread responds to a cancellation request.

4. Kernel Code to terminate process
Regardless how the process is terminated, the kernel code will close all open file descriptors, release the memory etc.

5. Exit Status
For all terminated process, we want them to notify their parents how they are terminated. This is done by passing the argument to exit, _exit, _Exit. Note, the argument we pass in is exit status, it will be converted to termination status

6. Parent Process terminated
What if parent process get terminated before the child process. Then kernel will scan through all active processes who are the children of terminating process, if yes, it will assign init process(id 1) as its new parent process.

7. Child Process terminated
What if child process get terminated before the parent process. The kernel will keep a small amount of child process's information like: process id, termination status, and CPU time taken by the process. Then parent process could use wait/waitpid function to retrieve the child process information.

8. Zombie Process
For child process who has terminated but its parent has not yet waited for it, it is called a zombie process.

9. Process inherited from init terminated
The init process is designed to use wait function to fetch the termination status whenever the process inherited from init get terminated.

No comments:

Post a Comment