Multi-process programming is pulling Monkey monkey hair - change apes

Our bravest and best lessons are not learned through success, but through misadventure .-------- our best lessons are not learned through success, but through misfortune.


Black multi-process programming like the Monkey King as trichotillomania, hair pulling is a fork (), they would copy their skills to the new Monkey King, but there are a unique place, then the new avatar will buckle down Other things.

1, process review

The difference between the program and the process: the program is running and occupied system resources (CPU time slice, memory, etc.) is called a process, a process can execute multiple programs.
For example, you usually open QQ is a process.

Want to learn more about the process of the students can be the venue

https://blog.csdn.net/weixin_46027505/article/details/104812719

  • Can be used under Linux system

ps aux command to view all process ID
Linux to stop a process running the command: kill [process ID] or killall [process name]
Linux process running a stop function:int kill(pid_t pid, int sig);

Gets the process ID of the function:

pid_t getpid(void);     //获取自己进程ID
pid_t getppid(void);   //获取父进程ID     

2. Review of process memory space

This part of another black wrote a blog, students can unfamiliar venue:
https://blog.csdn.net/weixin_46027505/article/details/105076010

Moreover, on the zombie blog:

https://blog.csdn.net/weixin_46027505/article/details/105097361

3, the system calls fork ()

Under Linux there are two basic system calls can be used to create child process: fork () and vfork (). fork is "fork" means in English. Why did you choose this name? Because a process running, if you use a fork, it gave rise to another process, so the process will "fork", so the name made very image.

  • After the fork, the operating system will be an exact copy of the parent process child process, although the father-son relationship, but it seems in the operating system, they are more like brother relationship, the two processes share code space, but the data are independent of space , the contents of the child data space is a complete copy of the parent process, is also the same as the instruction pointer, the child has a position (value of the program counter pc two processes currently running to the same parent process, i.e., from the child process is fork return at the beginning of execution).
  • In this way you can imagine, it has been running two processes simultaneously and in unison, after the fork, they were as different jobs, which is the bifurcation. As to which one of the first run, the operating system process scheduling algorithm related, and that the issue is not important in practical applications, if needed parent and child collaboration, can be resolved by way primitive.
#include  <sys/types.h>
#include  <unistd.h>
pid_t         fork(void);

The new process created by fork () is called the child process. fork () function is called once, but twice to return.
Return Value = 0: the child process is running, fork () returns 0
is greater than 0: running the parent process, fork return process is a child process's ID.
Less than 0: Error

  • 说明
  • After we call fork (), which requires the return value to determine the current code is running in the child process or parent process,
  • The reason fork function call failed for two main:
  1. The system has too many processes;
  2. The actual total number of processes a user ID exceeds the system limit.
  • The reason for the child returned to the parent process id is: a child process because the process can be more than one, not a function of the process so that a process can obtain all of its child processes id.
  • A child process, the reason fork returns 0 to it, because it can be called at any time getpid () to get their pid; can also call getppid () to get the id of the parent process.
  • Usually after we fork () will be in the child process exec () to perform other things.
  • Code which the child is a copy of the parent process, it will get the parent process text segment, segment data, heap and stack copies, so that his son will continue the process fork () after. But the parent and child do not share these storage space, but the parent and child share the text segment.
  • Father and son who should perform the newly created process is not specified, the call is determined by the system

下面我们给出示例代码,进一步理解fork()

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv)
{

    pid_t          pid;
    int            a=10;

    printf("before fork\n");
    printf("Parent process PID[%d] start running...\n", getpid() );
    pid = fork();
    if(pid < 0)
    {
        printf("fork() create child process failure: %s\n", strerror(errno));
        return -1;
    }
    
    //下面是子进程空间
    else if( pid == 0 )
    {

        a+=5;
        printf("Child process PID[%d] start running, my parent PID is [%d] \n", getpid(), getppid());
        printf("son a=%d\n",a);
    }
//下面是父进程空间
    else if( pid > 0 )
    {
       sleep(5);  //父进程阻塞在这里,让子进程先跑
        a+=10;
        printf("Parent process PID[%d] continue running, and child process PID is [%d]\n", getpid(), pid);
        printf("parent a=%d\n",a);

    }
    printf("after fork....\n");

    return 0;
}

Here Insert Picture Description

We observe the operation results of the parent and child processes are to a conduct their own operations on the original value of the global variable, indicating a = 10 between parent and child have their own separate space, without disturbing each other,
and we found that after fork Print twice, because running a child process exits, the parent process exits also run.
Here Insert Picture Description

4, the system calls vfork ()

Before you copy (specific description will be after this) when implementing write, Unix designers have been very concerned about the implementation of the waste caused by exec address space immediately after the fork.
Such predecessors bigwigs came up with vfork ()

  • vfork () function prototype and prototype fork as:
#include <unistd.h>
#include <sys/types.h>
pid_t fork(void); 
pid_t vfork(void);

In addition to the child process must be executed immediately once the exec system call, or by calling _exit () exit, a successful call to vfork () generated results and fork () is the same.

5 difference, fork and the vfork

fork() vfork()
Data segment and code segment sub-process copy of the parent process Child share data segment and the parent process, when it is desired to change the value of the shared variable data section, the copy of the parent process.
The execution order of parent and child processes uncertainties To ensure that the child processes to run first, before calling exec or exit the parent process data is shared, after it calls exec or exit the parent process can be scheduled to run before.
Parent and child processes independent of each other If these two functions before calling a child process depends on the further action of the parent process, it will lead to a deadlock.

Why vfork, because the previous fork silly, when it creates a child process, will create a new address
space, and a copy of the resources of the parent process, and often in the child process executes exec calls, so that the front of the copy work
for is in vain, and
in this case, smart people come up with vfork, the child just started it produces temporary and
shared address space (in fact, the concept of threads) parent process, because this time the child process in the address space of the parent process in the
run, so the child can not write, and his son "occupied" the father of the house when I wronged to a
down and let him recover from the outside (blocking), once his son executed after the exec or exit, relative to his son bought his own
house, this time with respect to the separation.
// This is seen above from the Internet, I feel good , specific forget where he comes from, you can not attach a link, if the original author to see, then, hope and understanding, you can leave a message, I attach a link back.

vfork () is a historical relic, Linux should not implement it. Note that, even when increased copy writing, vfork () also () fast, because the copy of the page table entry it no better than fork. However, the copy-on-write appearances were reduced () argument for replacement fork. In fact, until the kernel 2.2.0, vfork () package had only a fork (). Because the demand for vfork () is less than fork (), so vfork () of this implementation is feasible.

6, write copy

Linux uses a copy-on-write method to reduce the overhead of the parent process fork process overall copy space brings.
after fork () often followed by calls exec to execute another program, and exec will abandon the parent text segments, such as data and stack and load another program, so now a lot of fork () implementation does not execute a parent process data segment, heap and stack full copy of the copy.

Copy-on-write is an optimization method inert taken to avoid the overhead of copying.

Its premise is simple: If there are multiple processes to read their own copy of that department resources, then the copy is unnecessary. Each process just to save a pointer to the resources on it. As long as there is no process to make amendments own "copy", the existence of such an illusion: each process seems to monopolize the resource. Thereby avoiding the burden caused by replication. If a process to modify their share of resources, "copy", then it will copy the share of resources, and to provide to the copy of the process. However, the copy of which is transparent to the process is. This process can be modified after the copy of the resource, while the share of other processes still had not been changed shared resource.
So this is the origin of the name: copying when writing.

The benefits of copy-on-write 6.1

The main benefits of copy-on-write is this: If the process has never been a need to modify the resource, you do not need to copy.
Benefits inert algorithms is that they try to postpone costly operation, until the necessary time will to do it.

6.2 Copy the expansion of knowledge-write

1, in the case of the use of virtual memory, copy (Copy-On-Write) is the basis of the page write. So, as long as the process does not change its entire address space, so you do not have to copy the entire address space. In the fork () After the call, the parent and child processes believe they have their own address space, but in fact they share the parent's original page, then these pages and can be shared with other parent or child process.

2, copy the kernel write implementation is very simple. Kernel data structures associated with the page may be marked as read and write only copy. If any process attempts to modify a page, it will generate a page fault. Kernel page fault handling way is to conduct a transparent copy of the page. Then cleared COW property page, it indicates that it is no longer shared with.

3, modern computer system architecture provides hardware-level replication support when writing memory management unit (MMU), it is very easy to achieve. When calling fork (), copy-on-write is a great advantage. Since then a large number of fork will be followed by exec, then copy the entire contents of the address space of the parent process to the child process's address space is a complete waste of time: if the child process executes a new binary executable images at once, its previous address space will be swapped out. Copy this situation can be optimized write.

7, the child inherits the parent process something

Inherited by the child from the parent process to:
qualification process
environment (environment) variable stack
memory
open file descriptors
and so on. . .
Unique sub-process:
process ID
different parent process ID
and so on. . .
This part can access their own

8, other API functions

exec*()

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[]);

Above 7 different functions are called the exec function, then fork () after a re-call any of these functions will make the process of implementation of the newly created another program.

  • Which execl () argument is relatively simple, it is used more
    Usage:
    execl ( "where the program path", "command", "parameters of command", NULL);

wait()和waitpid()

wait and waitpid function is used to handle dead process.
Xu black Prior wrote a related blog:
https://blog.csdn.net/weixin_46027505/article/details/105097361

System () (caution) and popen ()

If we are in a program, you want to perform another Linux command, you can call fork () and then perform the appropriate exec command can be, but this is relatively trouble. Linux system provides a system () library function, the library function can quickly create processes to execute the appropriate command.

int system(const char *command);
  • For example
    system("ping -c 4 -I eth0 4.2.2.2");
    // execute the ping command

These two functions Students can search for additional learning related blog

Published 29 original articles · won praise 65 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_46027505/article/details/105141592