当前位置:网站首页>UNIX Environment advanced programming --8- process control ---8.5 function exit-8.6 function wait and waitpid
UNIX Environment advanced programming --8- process control ---8.5 function exit-8.6 function wait and waitpid
2022-06-13 09:36:00 【LuckyDog0623】
Process exit
One 、 Introduce background
Recently, I encountered a problem in my work , The background is :
init The process creates pc process ,pc The process creates pro1 process ,pro1 Will create pro2,pro3 and pro4 Three secondary processes , however pro1 The created secondary process will be handed over to pc management ; Due to the order of mutual dependence between threads ; Now the demand is pro1 After the process is completely killed, other processes can be killed , Get up, too pro1 Only when you get up completely can you start other processes ; But because of pro1 Initialize multiple , It takes a long time , There is a problem with sending signals directly and continuously to various processes ;
system("kill pro1");
system("kill pro2");
system("kill pro3"); There is no guarantee that 1 The process is dead
3、 If the child process exits before the parent process , So how can the parent process get the termination status of the child process when doing the corresponding check ? If the child process disappears , The parent process will not be able to get the status of the child process ; The kernel stores a certain amount of information for each terminating process , So when the parent process of the terminating process calls wait perhaps waitpid when , You can get this information ; This information includes at least the process ID, The termination status of the process and the CPU Time ;
If the child process becomes a zombie process after the parent process ends , Who will adopt this zombie process ?? When this zombie process terminates, who will clean up its exit status ??a process fork 了 b process ,b process fork 了 c process , And it's over , Who will clean up c The exit status of the process ??
Process termination process
Linux in . Release of resources , What is taken is “ Who applies for release ” Principles . example . Semaphores requested by the process itself 、 Document description, narrator, etc , The process needs to release itself . And the process description narrator 、 The kernel stack requires the parent process to recycle these resources .
The resources of the process itself are released
No matter how the process terminates . Will eventually call do_exit() function .do_exit() A function is a destructor of a process .
Borrow an online map , Performance examples are as follows :

do_exit() The function mainly completes the following work :
- take task_struct( The data structure that represents a process in the kernel ) Flag members in are set to PF_EXITING.
- call del_timer_sync() Delete any kernel timer .
- hypothesis BSD The process accounting function of is enabled , call acct_update_integrals() Output accounting information .
- call exit_mm() function , Release the mm_struct.
- call sem_exit() function . Release the semaphore of the process .
- call exit_files() and exit_fs(), Decrements the reference count of file descriptor and file system data respectively .
- Put it in storage task_struct Of exit_code Set the task exit code in the member to exit() Exit code provided .
- call exit_notify() Signal the parent process . Find the parent process again for the child process , The new parent process is another process in the process group or init process . And set the process status to EXIT_ZOMBIE.
- do_exit() call schedule() Switch to a new process .
Due to the EXIT_ZOMBIE Processes in state will no longer be scheduled , So this is the last piece of code for the process to run . After running the above operations , All the resources associated with the process are released , And in EXIT_ZOMBIE state . But the kernel stack of the process 、thread_info( Point to task_struct Data structure of ) and task_struct. At this time, the only purpose of the process is to provide information to the parent process . The parent process releases the remaining memory occupied by the child process .
Release the remaining resources of the process
When a process terminates , The kernel sends... To its parent process SIGCHLD The signal ( When ?). The parent process is in SIGCHLD In the signal processing function of wait() function , After obtaining the information of the terminated child process , call release_task() function , Release the remaining resources it occupies .
Suppose the parent process creates a child process , But I don't want to be responsible for recycling the resources occupied by the child process . Can be used twice fork Methods :
The parent process creates a child process , The child process creates the operations that the child process needs to run . Then the subprocess exits .
Because the subprocess exited . Then the sun process will be init Process hosting . Therefore, the system will also be responsible for the recycling of its resources .
Two 、 function exit
The process includes 5 Normal termination status and 3 An abnormal termination state
1、 stay main Function execution return Equivalent to exit;
2、 call exit function ;
3、 call _exit perhaps _Exit function
4、 The last thread of a process executes in its startup routine return sentence ; Note that the return value of this thread is not used as the return value of the process
5、 The last thread of the process calls pthread_exit function
3 An abnormal termination :
(1) call abort, It produces SIGABRT The signal , This is a special case of the next abnormal termination ;
(2) When a process receives a signal 、
(3) The last thread pair “ Cancel ”(cancelltion) request , By default ,“ Cancel ” In a delayed manner : One thread asked to cancel another , After some time , The target thread terminates .
Need to understand these separately Detailed process of termination method :
3、 ... and 、wait and waitpid
wait and waitpid function
When a process normally terminates or terminates , The kernel sends... To its parent process SIGCHID The signal , Because subprocess termination is an asynchronous event , It can happen at any time , The parent process can choose to ignore the signal or choose to capture the signal ;
use wait perhaps waitpid process :
1、 If all child processes are running , The block ;
2、 If the child process has terminated , Waiting for parent process to get its termination status , Get the termination status of the child process and return to ;
3、 If there are no child processes , Return immediately ;
pid_t wait(int *status);//NULL It means that you don't care about the status of exiting
pid_t waitpid(pid_t pid, int *statloc, int option);//option This allows the caller not to block , Successfully returned the... Of the exiting process pid
pid == -1 Any process , and wait equally
pid > 0 Specify process
pid == 0 Waiting group ID Equal to call group ID Any child process of
pid <-1 Waiting group ID be equal to pid Any child process of absolute value
4、 Parameters statloc It's an integer pointer , If statloc Not a null pointer , Then the termination state is stored in the unit it points to , If you don't care about termination , This parameter can be specified as NULL
5、 have access to 4 A mutually exclusive macro to get the reason for the process termination :// Judge status Whether a bit in is true
WIFEXITED(status) If it is the normal termination subprocess state , It is true
WIFSIGNALED(status) In case of abnormal termination , It is true
WIFSTOPPED(status) If it is the return status of the currently suspended child process , It is true
WIFCONTINUED(status) If the child process that has resumed after the job control is suspended returns to the state ; Operation control ?????
6、 Exit status processing print
void pre_exit(int status)
{
if(WIFEXITED(status ))
printf("normal termination, exit status = %d\n", WEIXTSTATUS(status));
else if(WIFSIGNALED(status))
printf("abnormal ternimal, signal number = %d %s\n", WIERMSIG(status), WCOREDUMP(status) ? " (core file generated)" : " ")
}
7、 Generate different interrupt signals
int main()
{
pid_t pid;
int status;
/************ The signal 1***************/
pid = fork();
if(pid == 0) // Subprocesses
{
exit(7);
}
if(pid != wait(&status))
printf("error");
pr_exit(status);
/************ The signal 2***************/
pid = fork();
if(pid == 0)
{
abort(); // produce SIGABRT
}
if(pid != wait(&status))
printf("error");
pr_exit(status);
/************ The signal 3***************/
pid = fork();
if(pid == 0)
{
status /= 0 ; // Divide 0, produce SIGFPE The signal
}
if(pid != wait(&status))
printf("error");
pr_exit(status);
return 0;
}8、 If fork A subprocess , But it doesn't wait for the child process to terminate , Nor do you want the child process to be zombie until the parent process terminates ; That is to create a process , Make its parent process init
{
pid_t pid;
pid = fork();
if(pid == 0)
{
pid = fork();
if(pid > 0)
{
exit(0);
}
sleep(2);
printf("second child, parents pid = %d\n", (long)getppid());
exit
}
if(waitpid(pid, NULL, 0) != pid)
printf("error\n");
exit(0);
}
边栏推荐
- 【pytorch环境安装搭建】
- LeetCode 5289. Fair distribution of cookies (DFS)
- LeetCode 6097. 替换字符后匹配(字典)
- (topological sorting +bfs) acwing 848 Topological sequence of digraph
- Overloading of typical operators
- Jenkins integrates LDAP. The problem of login failure of Jenkins users caused by LDAP configuration error is solved
- Classes and objects - initialization and cleanup of objects
- C language: preprocessing in program environment
- LeetCode 5259. Calculate the total tax payable
- LeetCode 583. 两个字符串的删除操作
猜你喜欢

Tree and binary tree: application of binary tree traversal

Tree and binary tree: storage structure of binary tree
![1-4 message passing interface [CSP authentication]](/img/db/aecda548693cdfb0e740bcf1a1c823.jpg)
1-4 message passing interface [CSP authentication]

Standard template library (STL)

Trees and binary trees: traversal of binary trees

acwing 788. Number of pairs in reverse order

Solov2 nanny level tutorial (including environment configuration, training your own data set, code logic analysis, etc...) Updating ing

Consolas-with-Yahei

C language: recursive function to realize Hanoi Tower

Classes and objects -- Inheritance
随机推荐
turtle库的使用数字时钟模拟时钟动态显示
(state compression dp+ binary) acwing 91 Shortest Hamilton path
Figure: concept of figure
Exercise 7-10 finding specified characters (15 points)
C/s model and P2P model
Instruction level parallelism (?)
C language: file operation
C language: minesweeping
C language: Address Book
Consolas-with-Yahei
VDD,DVDD,AVDD,VCC,AFVDD,DOVDD,IOVDD
C language: deep understanding of pointers and arrays
Acwing 787. Merge sort
LeetCode 322. 零钱兑换
VDD,DVDD,AVDD,VCC,AFVDD,DOVDD,IOVDD
LeetCode 343. integer partition
1-4 message passing interface [CSP authentication]
LeetCode 6098. 统计得分小于 K 的子数组数目(前缀和+二分查找)
C language: data storage in memory
LeetCode 201. 数字范围按位与