[Linux] Process creation and exit

Create process

pid_t fork(void)

Create child process by copying parent process, parent and child process code sharing, unique resources

The return value of fork(): (used to distinguish between parent and child processes)
parent process, return the pid of the child process, greater than 0
child process, return 0
and return -1 when an error occurs
Insert picture description here
Insert picture description here

pid_t vfork(void)—This method is rarely used

-Create a child process and block the parent process, the parent and child processes share the virtual address space
-If the parent and child processes run at the same time, it will cause stack confusion, so vfork () blocks the parent process and let the child process run first until the child process exits or the program is replaced After the parent process can continue to run

Copy-on-write

The child process is created by copying the parent process, so the parent and child processes map the same physical memory address at the beginning, but when the data needs to be changed, new space is opened for the child process and the data is copied.
Advantages: creating the child process efficient

Exit process

1. The return in the main function

Only the return in the main function can exit the process, not elsewhere

2. Library function void exit(int status)

The exit process can be called at any position, and the buffer is refreshed before exiting

3. System call interface _void exit(int status)

The exit process can be called at any position. If the buffer
status is not refreshed, it can be regarded as the exit return value of the process, that is, the exit reason of the program, which is saved in the pcb.
Use ehco &? The command can get the status value of the last exited process

Check the reason for the last system call usage error

1、void perror(const char* s);

Print a system error message
const char* s for user-defined remarks, for example:

Insert picture description here
Insert picture description here
Indicates that the program ran successfully without errors.
2. char *strerror(int errnum);

errnum-global variable, program error serial
number to obtain error information by program error serial number

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/115049666