当前位置:网站首页>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 anddemo
Related 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_t
It'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 )
perhapsexit
after , 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 = 30
As 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 sharesnum
Variable .
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 )
perhapsexit
after , The parent process is scheduled to executevfork()
Ensure that subprocesses run first , In the child process callexec
orexit
Then 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.
边栏推荐
- Create an interactive experience of popular games, and learn about the real-time voice of paileyun unity
- Architecture: load balancing
- JVM foundation review
- Xcode real machine debugging
- Architecture: database architecture design
- 35 pages dangerous chemicals safety management platform solution 2022 Edition
- 数组常用操作方法整理(包含es6)及详细使用
- Angled detection frame | calibrated depth feature for target detection (with implementation source code)
- MySQL advanced learning notes (III)
- Go自定义排序
猜你喜欢
Which software can translate an English paper in its entirety?
What are the recommended thesis translation software?
Talk with the interviewer about the pit of MySQL sorting (including: duplicate data problem in order by limit page)
Custom throttling function six steps to deal with complex requirements
Should you study kubernetes?
论文的英文文献在哪找(除了知网)?
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)
Xcode real machine debugging
Chinatelecom has maintained a strong momentum in the mobile phone user market, but China Mobile has opened a new track
Sysdig analysis container system call
随机推荐
Architecture: database architecture design
Pytorch 20 realizes corrosion expansion based on pytorch
NC24840 [USACO 2009 Mar S]Look Up
Feature Engineering: summary of common feature transformation methods
Bloom filter
Architecture: load balancing
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
redis21道经典面试题,极限拉扯面试官
S12. Verify multi host SSH mutual access script based on key
Judge whether the binary tree is full binary tree
Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
大学生课堂作业2000~3000字的小论文,标准格式是什么?
Mutual exclusion and synchronization of threads
[reading notes] phased summary of writing reading notes
NC20806 区区区间间间
Program analysis and Optimization - 9 appendix XLA buffer assignment
What website can you find English literature on?
[target detection] r-cnn, fast r-cnn, fast r-cnn learning
LeedCode1480.一维数组的动态和
国外的论文在那找?