当前位置:网站首页>Process control (creation, termination, waiting, program replacement)
Process control (creation, termination, waiting, program replacement)
2022-07-07 11:06:00 【Exy-】
Process creation
pid_t fork() and pid_t vfork()
The process is essentially a PCB, Creating a process is equivalent to creating PCB;
pid_t fork(void);pid_t vfork(void)
function : Create a new process by copying the parent process ( Subprocesses )
Return to child process id To the parent process , For child processes, return 0, Failure to return -1;
pid_vfork(void) characteristic : Parent and child processes share a virtual address space , Data sharing between parent and child processes. The modification of the original data by any process will affect the other party , And share the same stack , Therefore, function calls are pressed on the same stack , Cause stack chaos , So let the subprocess run first , After the subprocess exits , Or the parent process can run only after the program is replaced
about pid_t fork():
Think about it , If the parent-child process accesses the same global variable , Operation will definitely have an impact , Therefore, data should be unique between parent and child processes , Each has its own data .
After the subprocess is created , Reopen space for child processes , Copy the data of the parent process , Only in this way can we remain independent , But if the data is not accessed in the subprocess , Then the development of space and the copy of data are a waste of resources , For independence , And to provide efficiency , We use write time copy technology .
Copy while writing
When the thought sub process was first created , Let the child process be the same as the parent process , Mapping to the same physical memory , But if the data in a certain memory is about to change ( Either party needs to modify ), Then give the subprocess a new space for this piece , Copy data in the past .( Only open up the data space that needs to be modified )
Process termination
1. stay main Function return(return Only in main Function is to exit the operation of the program );
2. Library function : void exit(int status); You can call the exit program at any position stdlib.h
linux Next :man manual main 1- command main 2- system call man3- Library function
3. System call interface :void _exit(int status); Can be called anywhere , Exit the program unistd.h
Add : For standard output devices ,\n Will flush the buffer
The relationship between library functions and system call interfaces : Library functions encapsulate the system call interface
difference : Whether to refresh the buffer before exiting ;
exit And return The buffer will be flushed before exiting the program , Write data that has not been written to the file to the file
_exit Call to exit directly , The buffer will not be flushed , But directly release resources ( There may be data loss in the buffer )
echo $? Check the return value of the previous program
return The following numbers and exit Parameters of status The role of : Set the exit code of the process , And the exit code is only kept low 8 Bit in (0~255) Between .
Process waiting
Zombie process : The child process exits before the parent process , In order to save the exit code , Not fully releasing resources ;
Concept : Wait for the subprocess to exit , Get the exit code of the child process , Release child process resources , Avoid child processes becoming zombie processes ;
Although we don't care about the exit code of the subprocess , But still need to wait for the process , Avoid child processes becoming zombie processes , because
Subprocesses are harmful to the operating system .
operation :
int wait(int* status)
function : Blocking waits for any child process to exit , It means that if there are child processes and none of them exit, the process will be blocked and wait
Blocking waiting means : To accomplish a function , We initiate a call , If the function cannot be completed immediately, wait
Parameters :int *status One int Address of shaping space , Used to store exit code
Return value : Successfully return the processed exit subprocess pid, Failure to return -1
int waitpid(pid_t pid,int *status,int option)
Parameters :pid_t pid- Used to specify the child process waiting oid, If -1 It means waiting for any child process
int *status- The integer space address is used to obtain the exit code ;
option Used to set blocking flag 0- It means blocking and waiting ;WNOHANG- Indicates non blocking wait
function : It is also waiting for the child process to exit , But you can wait for the specified child process , And non blocking waiting
Return value : Greater than 0 Indicates the exit subroutine of the process pid; be equal to 0 Indicates that there are no child processes exiting ( Non blocking ); Less than 0 It means that something has gone wrong
Non blocking waiting : To accomplish a function , We launched a call , If the function cannot be completed immediately, the interface will immediately report an error and return
wait(&status)=wait(-1,&status,0)
Before waiting for the process , What about the child process that has exited ?
wait/waitpid Not just dealing with child processes that just quit , But as long as a child process exits , Those that have become zombie processes will be handled , That is, if there is a process that has exited , Just process it directly and return
The nature of program crash : An exception occurred during the operation of the program , All detected by the kernel , When a program runs abnormally , Then the system sends an abnormal signal to the process after monitoring ( Indicates that an abnormal event occurred in the process , Can't be running ), Only the abnormal signal value of the process is 0 When , Indicates that the program exits normally ; Otherwise, it is an abnormal exit
Get the abnormal exit signal value status & 0x7f Get the process exit code (status>>8) &0xff
WIFEXITED(status), The process exits normally and returns true;
Program replacement
It is to replace the program that a process is scheduling and managing , Usually used after creating child processes , Replace the program run by the child process ;
For example, web server , When a request comes , Create child process , Replace different handlers according to the request
exec Family of functions
Operation interface :
extern char **environ; This is a global variable , This variable holds all environment variables extern Just a statement , No space
int execve(char* pathname,char*argv[],char *env[]);
pathname: The pathname of the new program to be replaced
argv: The running parameters passed to the new program
env: Environment variables passed to the new program , Set to environ It means that the default existing environment variable is passed , If given by ourselves , So what you give is what you give ;
Return value : Successfully returns 0; Failure to return -1;
Be careful : Program replacement function, if the replacement is successful , Then the code after this function call will not be executed , Because the program has been replaced with a new program , And the new program will exit directly after running .
There are also some specific interfaces :
int execl(char* path,char *argv,...) path: Program pathname ; argv,... I don't know : The parameter is assigned to a single , There is no need to organize into pointer arrays , But in order to NULL ending ; Environment variables use the default existing
int execlp(char *filename,char *argv,...NULL)
filename: The program doesn't have to give a path , Only give names , Will automatically default to PATH Go to the path specified by the environment variable to find
int execle(char *path,char *argv,...,NULLchar *env[]) Compared with the above , Set the environment variables by yourself without using the default
int execv(char *pathname,char *argv[]); Program given pathname , You do not need to set environment variables to use the default
int execvp(char* filename,char *argv[]);
int execvpe(char *filename,char *argv[],char *env[]);
Be careful :
- If you replace all the instruction programs , Then take p, Don't give a path
- If you do not need to set environment variables , You don't need to bring e, Use default
- Parameters are used according to your data organization l still v,l Parameters are individually assigned ,v It is the organization of parameters into an array that gives
ordinary shell
Implement a simple one minishell, simulation shell The terminal uses the program to replace
#include<stdio.h>
#include<wait.h>
#include<unistd.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
while(1)
{
printf("kali~dev$");// Because there is no line break , So the data does not flush the buffer , Can't print out
fflush(stdout);// Refresh the standard output buffer ;
char cmd[128]={0};
fgets(cmd,127,stdin);// Get a row of data from standard input , If a line is too long , Just get 127 Bytes
cmd[strlen(cmd)-1]='\0';// Wrap the line at the end of the string , Replace with the end sign
// Parse string
char argv[32][32]={
{0}};
int argc=0;
int count=0;
char *ptr=cmd;
while(*ptr!='\0')
{
if(*ptr!=' '&&*ptr!='\0')
{
count=0;
while(*ptr!=' '&&*ptr!='\0')
{
argv[argc][count]=*ptr;
count++;
ptr++;
}
argc++;
}
ptr++;
}
char *myargv[32]={NULL};
for(int i=0;i<argc;i++)
{
myargv[i]=argv[i];
}
pid_t pid=fork();
if(pid==0)
{
int ret=execvp(argv[0],myargv);
if(ret<0)
{
perror("execvp error");
}
exit(0);
}
wait(NULL);
}
return 0;
}
边栏推荐
- How to successfully pass the senior system architecture designer in the second half of the year?
- Poj1821 fence problem solving Report
- Simple and easy to modify spring frame components
- P1031 [noip2002 improvement group] average Solitaire
- When initializing 'float', what is the difference between converting to 'float' and adding 'f' as a suffix?
- Using tansformer to segment three-dimensional abdominal multiple organs -- actual battle of unetr
- 2022.7.3DAY595
- Seata 1.3.0 four modes to solve distributed transactions (at, TCC, Saga, XA)
- The seventh training assignment
- 香橙派OrangePi 4 LTS开发板通过Mini PCIE连接SATA硬盘的操作方法
猜你喜欢
随机推荐
Qtcreator sets multiple qmake
【机器学习 03】拉格朗日乘子法
从色情直播到直播电商
软考中级电子商务师含金量高嘛?
JSON format query of MySQL
高级软考(网络规划设计师)该如何备考?
软考一般什么时候出成绩呢?在线蹬?
Laya common script commands
How to prepare for the advanced soft test (network planning designer)?
在线硬核工具
從色情直播到直播電商
Transaction rolled back because it has been marked as rollback-only解决
uniapp 在onLaunch中跳转页面后,点击事件失效解决方法
seata 1.3.0 四種模式解决分布式事務(AT、TCC、SAGA、XA)
"Dream Cup" 2017 Jiangsu information and future primary school summer camp it expert PK program design questions
[système recommandé 01] rechub
2022.7.6DAY598
【推荐系统 01】Rechub
How to successfully pass the senior system architecture designer in the second half of the year?
【推薦系統 01】Rechub