当前位置:网站首页>Multiprocess programming (I): basic concepts
Multiprocess programming (I): basic concepts
2022-07-03 00:23:00 【HDD615】
1、 Basic concepts
- process : An executing application , It's the operating system Resource allocation The basic unit of
- Threads : It is a specific task in the application being executed , It's the operating system Resource scheduling The basic unit of
- The relationship between processes and threads :
A process can include many threads , Provide necessary resources for threads , All threads share these resources . Each thread is responsible for completing a specific task , Threads cooperate with each other , Jointly ensure the normal operation of the process . meanwhile , Threads also have their own private resources .
2、 State of process
- The ready state 、 Running state 、 Blocking state

Running state : The process owning processor is running
The ready state : The process has the conditions to run , Waiting for system to allocate processor , Then start running
Blocking state : Processes cannot run directly , Waiting for an event to end , Then enter The ready state
Linux In the environment , View the filter process shell command
ps -ef: View all processes of the systemps aux: View all processes of the systemps -ef | grep demo: From all processes , Filter out anddemoRelated process- Kill process :
kill -9 pid_t
3、 Create a process
fork()
- Required header file
#include <sys/types.h> #include <unistd.h> - Used to generate a child process , Function return value
pid_tIt's an integer , In the parent process , The return value is the sub process number ; In the subprocess , The return value is 0. If the creation fails , Then return to -1.pid_t fork(void); - characteristic :
1、fork()The child process created by the function is a complete copy of the parent process , Copied the resources of the parent process
When writing copy : Just after the subprocess is created , Parent child processes are shared with variables , As long as any process performs a write operation on the data , Replication happens ( Data is not shared , First is the page break , Then the operating system allocates memory to the child process , And copy the data of the parent process ).
2、 Child processes have their own virtual address space , Parent child process data is unique , Code sharing (fork() Code after function)
3、 According to the return value , To determine whether it is a parent process or a child process - give an example :
Printout#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { pid_t res; res = fork(); if (res > 0) { printf("This is parent, pid = %d\n", getpid()); } else if (res == 0) { printf("This is child, pid = %d\n", getpid()); } else { perror("fork"); } return 0; }This is parent, pid = 3543 This is child, pid = 3544
vfork()
Required header file
#include <sys/types.h> #include <unistd.h> pid_t vfork(void);characteristic :
1、 Return values andfork()The same function .
2、vfork()Do not create virtual addresses of child processes , Directly share the parent process , So the physical address is also shared
3、 Subprocesses run first , In the child process callexec( Process replacement )perhapsexitafter , The parent process is scheduled to executegive an example :
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> int main() { int num = 10; pid_t res; res = vfork(); if (res > 0) { printf("This is parent, pid = %d\n", getpid()); num += 10; printf("num = %d\n", num); } else if (res == 0) { printf("This is child, pid = %d\n", getpid()); num += 10; printf("num = %d\n", num); exit(0); } else { perror("vfork"); } return 0; }Printout
This is child, pid = 4495 num = 20 This is parent, pid = 4494 num = 30As can be seen from the output , The subprocess executes first , In the child process call
exit(0)After you quit , The parent process executes again .
also , The parent-child process sharesnumVariable .
fork() and vfork() The difference :
fork()Copy the page table entry of the parent process , When writing , The kernel allocates a new memory page to the child processvfork()Share page entries with the parent process , When writing operations , Write directly on the memory page of the parent processfork()The execution order between the created child process and the parent process is uncertainvfork()It is the subprocess that runs first , In the child process callexec( Process replacement )perhapsexitafter , The parent process is scheduled to executevfork()Ensure that subprocesses run first , In the child process callexecorexitThen the parent process can be scheduled to run . If in
Before calling these two functions, the child process depends on the further actions of the parent process , It will lead to deadlock .
4、exec Family of functions
occasionally , We need to execute other programs in the subprocess , That is, replace the current process image , At this time will use exec Some functions in the function family .
** effect :** Find the executable file according to the specified file name , And replace the contents of the calling process with it ( Execute an executable file inside the calling process )
Return value :exec The function of the function family does not return , Only the call failed , Will return -1, Go back to the call point of the source program and proceed .
Common functions :
1、
int execl(const char *pathname, const char *arg, ...); - pathname: The path of the executable file to execute - arg: A list of parameters required to execute the executable arg Generally, fill in the name of the current execution program , Followed by a list of parameters required by the executable program , Parameters should end with NULL end . - Return value : When the call fails , There is a return value , return -1.2、
int execlp(const char *file, const char *args, ...); - and execl Almost the same , But for the file Will look for from the environment variables .
5、 Orphan process
Definition : The parent process ends running , But the child process is still running , Such a child process is an orphan process ( Father dead son in ).
Be careful : Whenever there is an orphan process , The kernel sets the parent of the orphan process to init, and init The process will cycle wait() Its child processes that have exited . So when an orphan process ends its life cycle ,init() The process will deal with all its aftermath .
therefore , The orphan process doesn't do any harm .
6、 Zombie process
When the child process ends running , The kernel does not immediately release the process table entry of the process , To meet the subsequent query of the parent process on the exit information of the child process ( If the parent process is still running ).
After the subprocess finishes running , Before the parent process reclaims the child process state , This sub process is a zombie process . Limited kernel resources , It is not allowed to generate a large number of zombie processes .
Zombie processes cannot be kill -9 Kill .
Can be used in the parent process wait() perhaps waitpid() function , To wait for the end of the child process , And get the return information of the child process , Thus, the generation of zombie process is avoided , Or make the zombie state of the child process end immediately .
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);
- function : Wait for any subprocess to finish , And recycle the child process .
- Parameters :wstatus, Status information when the process exits , What's coming in is a int Pointer to type ( Out parameter )
- Return value :
success : Returns the of the recycled child process id
Failure :-1( All subprocesses end , Call to function failed )
Be careful : call wait() The process of the function will be suspended ( Blocking ), It doesn't wake up until one of its child processes exits or receives a signal that can't be ignored .
If there are no child processes , The function immediately returns -1;
If all the child processes have ended , And will return immediately , return -1.
边栏推荐
- Sysdig analysis container system call
- Digital twin smart factory develops digital twin factory solutions
- Talk with the interviewer about the pit of MySQL sorting (including: duplicate data problem in order by limit page)
- LeedCode1480.一维数组的动态和
- Develop knowledge points
- 来自数砖大佬的 130页 PPT 深入介绍 Apache Spark 3.2 & 3.3 新功能
- Maya fishing house modeling
- redis21道经典面试题,极限拉扯面试官
- Returns the root node of the largest binary search subtree in a binary tree
- [target detection] r-cnn, fast r-cnn, fast r-cnn learning
猜你喜欢

RTP 接发ps流工具改进(二)

35 pages dangerous chemicals safety management platform solution 2022 Edition
![[target detection] r-cnn, fast r-cnn, fast r-cnn learning](/img/f0/df285f01ffadff62eb3dcb92f2e04f.jpg)
[target detection] r-cnn, fast r-cnn, fast r-cnn learning

TypeError: Cannot read properties of undefined (reading ***)

秒杀系统设计
![[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)](/img/c5/2f65d37682607aab98443d7f1ba775.jpg)
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)

67 page overall planning and construction plan for a new smart city (download attached)

redis21道经典面试题,极限拉扯面试官

直击产业落地!飞桨重磅推出业界首个模型选型工具

MySQL advanced learning notes (III)
随机推荐
zhvoice
Matlab 信号处理【问答笔记-1】
UART、RS232、RS485、I2C和SPI的介绍
教育学大佬是怎么找外文参考文献的?
Implement the foreach method of array
多进程编程(五):信号量
MySQL advanced learning notes (III)
Should you study kubernetes?
Chapter 4 of getting started with MySQL: data types stored in data tables
yolov5detect. Py comment
秒杀系统设计
MATLAB signal processing [Q & a notes-1]
Which websites can I search for references when writing a thesis?
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
Bypass AV with golang
[shutter] shutter open source project reference
免费自媒体必备工具分享
布隆过滤器
Cmake basic use
Shell脚本基本使用