Linux Process Control

Posted by McManCSU on Fri, 24 Dec 2021 23:30:27 +0100

preface

Today, we will introduce the relevant knowledge of process control in detail. Such as exit and_ The difference of exit function, the principle of fork function, virtual address space, process creation, process termination, process waiting, process program replacement and so on. Let's study together!

1, Process creation

1.1 introduction to fork function

fork function is a very important function in linux. It creates a new process from an existing process. The new process is a child process and the original process is a parent process.

The process calls fork. When the control is transferred to the fork code in the kernel, the kernel does the following:

  • Allocate new memory blocks and kernel data structures to child processes
  • Copy part of the data structure content of the parent process to the child process
  • Add a child process to the system process list
  • fork returns to start scheduler scheduling

Note: after fork, it is entirely up to the scheduler to decide who will execute first.

Return value of fork function:

  • The child process returned 0
  • The parent process returns the PID (process number) of the child process

Reason for fork call failure:

  • There are too many processes in the system
  • The actual user's process exceeded the limit

Inter process operation is preemptive:

For the child processes created by fork, the parent and child processes also execute preemptively when executing their own code.

1.2 virtual address space

Note:

  • 1. The address printed in the code is not a physical address, but a virtual address.
  • 2. The generation of virtual address is due to the birth of the operating system in order to facilitate the unified management of physical memory.
  • 3. The virtual address cannot save data, and the saved data is still saved in the physical address. Therefore, when a process uses a virtual address to access data, the operating system needs to find the physical address through the virtual address, so as to promote the process to access data.

Methods of converting virtual addresses into physical addresses: segmented, paged and segmented

1. Pagination:

Virtual address = page number + in page offset

Page number = virtual address / page size

In page offset = virtual address% page size

2. Sectional type:

3. Paragraph page type:

1.3 other concepts

Parallelism and Concurrency:

Parallel: multiple processes have different CPU s for operation at the same time, which is called parallel.

Concurrency: multiple processes can only have one process with CPU for operation at the same time, which is called concurrency.

Independence:

Multi process operation requires exclusive access to various resources and does not interfere with each other during multi process operation

2, Process termination

2.1 scenario of process exit

  • The code runs and the result is correct
  • The code has finished running and the result is incorrect
  • Code terminated abnormally

2.2 common exit methods of process

Normal termination:

  • 1. Return from main
  • 2. Call exit
  • 3. Call_ exit

Abnormal exit:

  • ctrl + c, signal termination

2.2.1 exit function and_ Principle of exit function

_ exit function

#include <unistd.h>
void _exit(int status);
Parameters: status Defines the termination status of the process. The parent process passes wait To get the value

This function is a system call function. Whoever calls it will exit.

Status: status code of process exit

exit function

#include <unistd.h>
void exit(int status);

This function is a library function. Whoever calls it will exit.

Status: status code of process exit

The exit function will eventually be called_ Exit, but before calling_ Other work has been done before exit:

  • 1. Execute the user-defined cleanup function
  • 2. Refresh buffer

2.2.2 exit function and_ Differences between exit functions

The exit function is called_ Before the exit function, use the atexit function or on_exit defines the cleanup function.

int atexit(void (*function)(void));
Parameter: the parameter is a function pointer type and accepts the address of a function
 The return value of the function is void,Parameters, too void

The atexit function registers a function mycallback, which is not called.

After the main function is completed, the mycallback function just registered will be called.

Execution steps of callback function:

  1. Registering Callbacks
  2. Call callback function

How to refresh the buffer:

1. After the return of the main function returns

2.fflush: forced refresh

3.\n

4.exit function

3, Process wait

3.1 necessity of process waiting

  • As mentioned earlier, if the child process exits and the parent process is ignored, it may cause the problem of "zombie process", and then cause memory leakage.
  • In addition, once the process becomes a zombie state, it will be invulnerable, and kill -9 can't do anything, because no one can kill a dead process.
  • Finally, we need to know how the tasks assigned by the parent process to the child process are completed. For example, when the subprocess runs, whether the result is right or wrong, or whether it exits normally.
  • The parent process reclaims the child process resources and obtains the child process exit information by waiting for the process.

3.2 method of process waiting

wait method

#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int*status);
Return value:
 Successfully returned to the waiting process pid,Failure Return-1. 
Parameters:
 Output type parameter to obtain the exit status of the child process,If you don't care, you can set it as NULL

waitpid method

pid_ t waitpid(pid_t pid, int *status, int options);
Return value:
 When returning normally waitpid Returns the process of the collected child process ID;
 If options are set WNOHANG,While calling waitpid No exited child processes were found to collect,Returns 0;
 If an error occurs in the call,Then return-1,At this time errno Will be set to the corresponding value to indicate the error;
Parameters:
 pid: 
 Pid=-1,Wait for any child process. And wait Equivalent.
 Pid>0.Wait for its process ID And pid Equal child processes.
 status:
 WIFEXITED(status): True if it is the status returned by the normally terminated child process. (check whether the process exits normally)
 WEXITSTATUS(status): if WIFEXITED Non zero, extract the subprocess exit code. (view the exit code of the process)
 options:
 WNOHANG: if pid If the specified child process does not end, then waitpid()The function returns 0 without waiting. If it ends normally, it will return to this child
 Cheng ID. 
  • If the child process has exited, when calling wait/waitpid, wait/waitpid will return immediately and release resources to get the child process to exit

    Send out information.

  • If wait/waitpid is called at any time and the child process exists and runs normally, the process may block.

  • If the child process does not exist, an error is returned immediately.

4, Process program replacement

4.1 replacement principle

The subroutine created with fork executes the same program as the parent process (but it is possible to execute different branch codes). Sub processes often call an exec function to execute another program. When a process calls an exec function, the user space code and data of the process are completely replaced by the new program and executed from the startup routine of the new program. Calling exec does not create a new process, so the process id before and after calling exec does not change.

4.2 substitution function

There are six functions starting with exec, which are collectively referred to as exec functions:

#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 execve(const char *path, char *const argv[], char *const envp[]);

4.3 function interpretation

  • If these functions are called successfully, a new program will be loaded and executed from the startup code without returning.
  • Returns - 1 if the call fails
  • Therefore, the exec function has a return value when an error occurs, and no return value when it is successfully executed

4.4 naming understanding

These function prototypes look easy to mix, but they are easy to remember as long as they master the rules.

  • l(list): indicates that the parameter adopts a list
  • v(vector): array of parameters
  • p(path): automatically search the environment variable PATH
  • e(env): indicates that you maintain environment variables

Example of exec function call:

#include <unistd.h>
int main()
{
 char *const argv[] = {"ps", "-ef", NULL};
 char *const envp[] = {"PATH=/bin:/usr/bin", "TERM=console", NULL};
 execl("/bin/ps", "ps", "-ef", NULL);
 // With p, you can use the environment variable PATH without writing the full PATH
 execlp("ps", "ps", "-ef", NULL);
 // With e, you need to assemble your own environment variables
 execle("ps", "ps", "-ef", NULL, envp);
 execv("/bin/ps", argv);
 
 // With p, you can use the environment variable PATH without writing the full PATH
 execvp("ps", argv);
 // With e, you need to assemble your own environment variables
 execve("/bin/ps", argv, envp);
 exit(0);
}

In fact, only execve is a real system call, and the other five functions eventually call execve, so execve is in Section 2 of the man manual, and other functions are in Section 3 of the man manual.

summary

The above is today's content, which introduces the related content of process control. Such as exit and_ The difference of exit function, the principle of fork function, virtual address space, process creation, process termination, process waiting, process program replacement and so on. I hope you will digest it carefully and gain something.

Topics: Linux Multithreading Operating System