The concept of process and the usage of exec

Posted by faza on Wed, 09 Mar 2022 09:45:54 +0100

I Process concept

1. The difference between process and procedure?
Uncompiled program ------------ executable program
Program: a pile of programs to be executed GCC hello C - O hello (program is a static data) script

Process: only when the program is loaded into the CPU and occupies resources, it can form a truly dynamic process by reacting to each line of code
(process is a dynamic process) the process of filming

2. Executable program project -- >/ Project -- > start a process

The data of the following areas will be copied directly from the program to memory

.initInitialization segment
. data and bssData segment
.rodataConstant area

3. When the program is executed, in addition to allocating space, the system will also allocate a structure directory for you. When reading a directory item, it will return a structure pointer, which is used to describe the directory item (Description: type, structure size, index number, offset, file name)

    ./project   Start a process  
      -->  Returns a structure  
      struct task_struct{};

This structure is used to describe the process (Description: process ID number, signal, file, resource...). Where is this structure?

/usr/src/linux-headers-3.5.0-23/include/linux/sched.h

4. Order on process

1) View the commands of the entire Linux System -- > pstree

//The ancestor processes of all processes are init processes. Init - ┬ - NetworkManager - {NetworkManager}
├─accounts-daemon───{accounts-daemon}
├─acpid
├─atd
├─avahi-daemon───avahi-daemon
├─bluetoothd
├─colord───2*[{colord}]
├─console-kit-dae───64*[{console-kit-dae}]
├─cron
├─cupsd

2) View process PID number -- > PS - ef (static)

3) View process CPU usage -- > top (dynamic)

CPU real-time utilization

5. Status of the process

Ready TASK_RUNNING waiting for CPU resources
Running task_ CPU resources consumed by running
Suspended TASK_STOPPED received pause signal
Sleep state
TASK_ Intermittent response signal -- > light sleep pause() -- > until a signal is received
TASK_ Unresponsive -- > deep sleep
Zombie exit_ When the zombie process exits, it will become a zombie state and occupy CPU resources
When a dead process exits, if a process recovers resources for itself, it will change from zombie state to dead state

CPU resources: refers to struct task_struct{};

II Process function interface

1. How to create a new process? -- > fork() --> man 2 fork

NAME
fork - create a child process / / when a child process is created in a process, the parent and child processes will execute together

//Header file
#include <unistd.h>

//Function prototype
pid_ t fork(void); --> No parameters need to be passed

//Return value: pid_t process ID number type

Success: the parent process returned the PID number of the child process. The child process returned 0. Failure: - 1

====================================================
#include <stdio.h>
#include <unistd.h>

int main()
{
	//1. When the program starts to execute, there is only one process
	printf("hello!\n");
	
	//2. Generate a sub process
	fork();
	
	//3. The parent-child process executes this code at the same time. As for who comes first and who comes later
	printf("world!\n");
	
	return 0;
}
========================================================

//Case 1: the parent process executes first and the child process executes later. Once the parent process ends, return 0 will be executed and the command line will appear
gec@ubuntu:/mnt/hgfs/01/code$ ./fork
hello!
gec@ubuntu:/mnt/hgfs/01/code$ world!

//Case 2: the parent process executes later and the child process executes first

gec@ubuntu:/mnt/hgfs/01/code$ ./fork
hello!
world!
gec@ubuntu:/mnt/hgfs/01/code$

Summary:
1) After fork(), the parent-child processes are executed concurrently
2) The parent-child process is executed at random
3) The PID number has no negative number

2. View its own PID number / view the PID number of the parent process

 getpid()         getppid()

getpid, getppid - get process identification / / get the corresponding ID number

//Header file
   #include <sys/types.h>
   #include <unistd.h>

//Function prototype
   pid_t getpid(void);  --> View your own ID number
   pid_t getppid(void); --> View the parent process of the current process ID number

Return value:
	Success: corresponding PID number
	Failed:  These functions are always successful.

III Before and after resource creation, parent-child difference?

  1. The child process inherits most of the resources of the parent process, and the PID number resource will not inherit.
  2. The space between father and son processes is independent of each other
#include <stdio.h>
#include <unistd.h>

int main()
{
	int a = 100;
	
	pid_t x = fork();
	if(x > 0)
	{
		a = 50;
		printf("parent a = %d\n",a); //50
	}
	
	if(x == 0)
	{
		printf("child a = %d\n",a); //100
	}
	
	return 0;
}

IV On the sub process, resource recycling.

Why recycle? -- > Free CPU resources

Process status
Running state: occupy CPU resources and run the code in the program
Zombie state: occupy CPU resources and do not run the code in the program
Dead state: it does not occupy CPU resources

2. Solve the zombie problem:

1) When the parent process of a process exits before itself, the system will specify init as the stepparent, wait for the child process to exit, and recycle the resources of the child process 2)
When the parent process is still running, the parent process actively reclaims the resources of the child process

There are two situations:
1. The parent process needs to last for a period of time before recycling. The child process will soon end its task and exit. When the child process exits, the child process will become a zombie state. After waiting for its parent process to finish the task, help the child process recover resources, and the child process will become a dead state

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	
	pid_t x = fork();
	if(x > 0)
	{
		int i;
		printf("hello,I am parent!\n");
		//2. Since the parent process has no time to listen, the child process is always in zombie state during the period of 2 to 20 seconds
		//3. Until 20 seconds, the parent process actively calls the wait function to reclaim the resources of the child process
		for(i=0;i<20;i++)
		{
			printf("hello!\n");
			sleep(1);
		}
		
		int state;
		//wait(NULL); // The parent process is not related to the exit state of the child process
		wait(&state); //Blocking waits until the child process exits
		printf("state = %d\n",state);
	}
	
	if(x == 0)
	{
		sleep(2);
		printf("I am child!\n");
		//1. The subprocess exits immediately and becomes a zombie
	}
	
	return 0;
}

2. The parent process is already monitoring the state of the child process before the child process exits, reclaiming the child process resources and making the child process become dead. After the child process exits, it becomes a zombie state and will be recycled by the parent process and enter the dead state immediately.

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	pid_t x = fork();
	if(x > 0)
	{
		int state;
		printf("hello,I am parent!\n");
		//wait(NULL); // The parent process is not related to the exit state of the child process
		wait(&state); //Blocking waits until the child process exits
		printf("state = %d\n",state);
	}
	
	if(x == 0)
	{
		int i;
		for(i=0;i<5;i++)
		{
			printf("hello!\n");
			sleep(1);
		}
		exit(1);
	}
	
	return 0;
}
  1. Interface for recycling child process resources – wait() / waitpid()
wait for process to change state

Function: monitor the status of sub processes

#include <sys/types.h>
#include <sys/wait.h>

   pid_t wait(int *status);

Status: pointer variable of the exit status of the monitored child process

Return value:
Success: the PID number of the child process that exited
Failed: - 1

waitpid() is an encapsulation of the wait() function -- > man 2 waitpid

#include <sys/types.h>
#include <sys/wait.h>

pid_t waitpid(pid_t pid, int *status, int options);

pid:

< -1    : Wait for the absolute value of this negative number ID Process of No
  -1    : Wait for any child process    And wait()
   0    : Waiting for any process in the process group
>  0    : Wait for the specified child process

Status: pointer variable of the exit status of the monitored child process

     options:    
     WNOHANG:    Listen for the exit status of the child process, but it is non blocking. This function will return immediately whether the child process exits or not at that time!   
     WUNTRACED:  Listen for the pause signal of sub process and block   
     WCONTINUED: Listen for the recovery signal of the subprocess and block    
     0 : Blocking (equivalent to wait())

The call wait(&status) is equivalent to: waitpid(-1, &status, 0);

4. Exit of the process

#include <stdlib.h>

void exit(int status);   ---> Clean the buffer before exiting

#include <unistd.h>

void _exit(int status);   ---> Exit directly without cleaning the buffer

V exec family

NAME
execl, execlp, execle, execv, execvp, execvpe - execute a file

SYNOPSIS

#include <unistd.h>
int execl(const char *path, const char *arg,...);
int execlp(const char *file, const char *arg,...);
int execle(const char *path, const char *arg,..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);

Path: the absolute path of the file to be executed. File: filename arg:
When executing the program, the required parameter list takes NULL as the end flag envp: environment variable

The exec function will not be replaced after the exec function is executed

Topics: Linux Operation & Maintenance server