当前位置:网站首页>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);
}
边栏推荐
猜你喜欢
[ssl1280] full arrangement
SQL ROW_ The number() function uses
Jenkins access openldap user authentication
C/s model and P2P model
C language: deep understanding of character functions and string functions (1)
[Luogu p1090, ssl1040] merged fruit [pile]
【pytorch环境安装搭建】
Classes and objects -- Inheritance
(Dijkstra + shortest circuit + by point n^2) acwing 849 Dijkstra finding the shortest path I
Figure: concept of figure
随机推荐
(bfs+GOOD) acwing 845. Eight digit
阿里高级专家剖析 | Protocol的标准设计
英国出台粮食安全计划抵御粮食供应危机
Haproxy + keepalived for high availability load balancing of MySQL
(bfs) acwing 844. Labyrinth
I have summarized the knowledge points of JS [intermediate and advanced] for you
Exploitation of competitive loopholes in attacking and defending world PWN play conditions
Can the operation of the new BMW I3 meet the expectations of the famous products of the 3 series?
Biden: hope to sign the bipartisan gun safety reform bill as soon as possible
List list
[51nod p3395] n-bit gray code [bit operation]
(state compression dp+good) acwing 291 Mondrian's dream
Online debugging tool Arthas advanced
1-2 24:00 (20 points) [CSP certification true question]
turtle库显示系统时间
[pytorch environment installation]
Classes and objects -- object model and this pointer
C language: summary of question brushing (1)
(dfs+ tree DP) acwing 846 Center of gravity of tree
[implementation of depth first search]