当前位置:网站首页>Interprocess communication (IPC)

Interprocess communication (IPC)

2022-07-07 11:06:00 Exy-

Catalog

One . The Conduit -PIPE

1. Classification of pipes

1.1 Anonymous pipeline

1.2 name pipes

2. The nature and characteristics of pipelines

2.1 The essence

2.2 characteristic

3. Pipe,

Two . Shared memory

1. Principles and characteristics

2. Operation process and interface

3、 ... and . Message queue

1. The essence

2. Communication principle

3. characteristic

Four . Semaphore

1. The essence

2. The principle of semaphore synchronization and mutual exclusion


Interprocess communication (IPC) The operating system provides several ways for users to communicate between processes ( The Conduit , Shared memory , Message queue , Semaphore )

Purpose : Process independence ( Each process has its own virtual address space , Access to their own virtual addresses , Other processes do not actually have this data in their own virtual address space mapping ), Therefore, there is no direct communication between processes , But in large projects, multiple collaborative work is common , At this time, inter process communication is particularly important .

Interprocess communication adopts different ways according to different actual application scenarios .

One . The Conduit -PIPE

Half duplex communication : The pipe has two ends , But the data from which end to which end is decided by the user

1. Classification of pipes

1.1 Anonymous pipeline

A buffer opened up in the kernel , No identifier , Cannot be found by other processes ( Can only be used for inter process communication with kinship )

for example : A process creates an anonymous pipeline in the kernel through system calls , In order to allow users to operate the pipeline , Therefore, the file descriptor is called as the operation handle of this pipeline , Other processes have no identifier because of this pipeline , Unable to find and therefore unable to communicate . however , If the process that created the pipeline creates a child process , At this time, the child process copies the parent process ( Document descriptor table ), Therefore, the subprocess is equivalent to having a file descriptor to operate the pipeline .

The operation handle of the same pipeline can only be obtained by copying the parent process by the child process .

int main(){
  // Anonymous pipes can only be used for interprocess communication with kinship , The child process obtains the operation handle by copying the parent process 
  // Be careful : Create a pipeline before creating a child process 
  int pipefd[2];
  int ret=pipe(pipefd);
  if(ret<0){
    perror("pipe error");
    return -1;
  }
  pid_t pid =fork();
  if(pid<0)
  {
    perror("fork error");
    return -1;
  }
  if(pid==0){
    // The subprocess writes data to the pipeline 
    char*str=" One day class , Uncomfortable ~! \n";
    write(pipefd[1],str,strlen(str)); 
  }
  else
  {
    // The parent process reads data from the pipeline 
    char buf[1024]={0};

    read(pipefd[0],buf,1023); 
    printf("read:%s",buf);
  }
  close(pipefd[0]);
  close(pipefd[1]);
  return 0;
}

1.2 name pipes

A buffer opened up in the kernel , With identifier , Can be found by other processes

name pipes : A process creates a named pipe , This named pipeline will create a pipeline file in the file system ( You can see , It's actually the name of the pipe ), Multiple processes open the same pipeline file , Access the same buffer in the kernel to realize communication , It can be used for any interprocess communication on the same host .

operation :mkfifo File create named pipe file

Interface :int mkfifo(char *filename,mode_t mode);

With p It starts with a pipeline file , Create named pipe file , It does not immediately create

2. The nature and characteristics of pipelines

2.1 The essence

A buffer in the kernel , Multiple processes access the same buffer to communicate , And it can't grow indefinitely ( Will cause resource depletion , System crash ).

2.2 characteristic

Anonymous pipe properties :

If there is no data in the pipeline , be read It will block ; If the pipeline is full , be write It will block

Blocking : To accomplish a function , A call , If the function cannot be completed, keep waiting

Non blocking : To accomplish a function , A call , If the function cannot be completed, call the error report and return

Other features : tube The operation of Tao will block , But if all write ends of the pipe are turned off ( It is no longer possible for the pipeline to write data ) Now read After reading the data in the pipeline, it is no longer blocked , And back 0( there 0 It means no one writes , Instead of no data )

All read ends of the pipe are closed ( Nobody in the pipeline reads the data ) Continued to write It will trigger an exception , Process exits

Name pipe properties :

Unique opening feature : If the named pipe file is opened read-only , It will block , Until the pipeline file is opened by other processes in writing

                           If the named pipe file is opened with write only , It will block , Until the pipeline file is opened by other processes in a read way

The principle is : The buffer of the pipeline is in the case that no process is sure to write data and there is a process reading data , There is no need to open up a buffer , Only when there is reading and writing can the buffer be opened , Otherwise, empty resources .

General characteristics :1. Half duplex communication

            2. The life cycle goes with the process

            3. Pipelines provide passage transmission ( Data first in, first out , All readers are closed write abnormal , All write ends are closed read return 0 It's not blocking )

             4. The pipeline has its own synchronization and mutual exclusion

              Sync : The operation is carried out in a certain order , No data read Blocking , The data is full write Blocking ,

              Mutually exclusive : The operation is safe and reliable , Only one process can access at a time ,, Avoid cross writing .

3. Pipe,

Pipe, : Connect two commands , The output result of the previous command , As the input of the next command, it is passed to the next command for processing

Implementation of pipeline symbol :

Let the previous command process , No longer write data to standard output , Instead, it is written into a pipeline

Let the following command process , No longer read data from standard input , Instead, it reads from a pipe

// Realize the function of pipeline symbol through anonymous pipeline 
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<wait.h>
int main(){
  int pipefd[2]={-1};
  if(pipe(pipefd)<0){
    perror("pipe error");
    return -1;
  }
  pid_t ps_pid=fork();
  if(ps_pid==0){
    //ps Subprocesses 
    close(pipefd[0]);
    dup2(pipefd[1],1);// Redirect the standard output to the pipeline writer , towards 1 Writing data in is equivalent to writing data to the pipeline 
    execlp("ps","ps","-ef",NULL);
    exit(0);
  }
  pid_t grep_pid=fork();
  if(grep_pid==0){
    close(pipefd[1]);
    //grep Subprocesses 
    // Redirect the standard output to the pipeline writer , towards 1 Writing data in is equivalent to writing data to the pipeline );
    dup2(pipefd[0],0);
    execlp("grep","grep","ssh",NULL);
    exit(0);
  }
  close(pipefd[0]);
  close(pipefd[1]);
  waitpid(ps_pid,NULL,0);
  waitpid(grep_pid ,NULL,0);
  return 0;
}

Two . Shared memory

1. Principles and characteristics

principle : Open up a new piece of physical memory , The process that needs to communicate maps this physical memory into its own virtual address space , Directly use your own user space address to access

characteristic : One of the fastest means of interprocess communication , Because memory is accessed directly through virtual addresses , Compared with other methods, there are two less copies of data between user space and kernel space , Its life cycle varies with the kernel .

Be careful : Shared memory is an overlay memory operation , And there is no mutually exclusive synchronization relationship , The operation needs to consider safety issues

2. Operation process and interface

(1) Create or open shared memory

int shmget(key_t key,size_t size,int shmflag)

key: Shared memory identifier

size: Size of shared memory to be created

shmflag:IPC_CREAT | IPCEXCL | 0664

IPC_EXCL And IPC_CREAT Use it with , Indicates that there is an error , If it does not exist, create and open

mode:0664 Set shared memory access

Return value : Successfully returned a non negative integer - Operation handle , Failure to return -1;

(2) Map shared memory to virtual address space

void*shmat(int shm_id ,void *shmaddr,int shmflag)

shm_id:shmget The returned operation handle

shmaddr: Usually set NULL, Let the system automatically allocate and establish mapping

shmflag:SHM_RDONLY- read-only ;0- The default is read-write ;

Return value : The first address of the mapping is returned successfully ; Failure to return -1;

(3) Memory operations

(4) Unmapping

int shmdt(void *shm_start)

shm_start: Mapping first address -shmat The return value of

Return value : Successfully returns 0; Failure to return -1;

(5) Delete shared memory ( In fact, we deleted , Shared memory will not be deleted immediately , Wait until the number of mapped connections to shared memory is 0 Will be deleted )shm_nattch( Number of mapped connections ) Once this shared memory is marked as being destroyed , Then this shared memory will no longer be mapped

int shmctl(int shm_id,int cmd,struct shmid_ds *buf)
shmid: Operation handle

cmd:IPC_RMID- Mark deletion ( No longer accept new mappings )

buf: Used to get shared memory information , If you don't need it, put it NULL)

Return value : Successfully returns 0; in the light of IPC_RMID Failure to return -1;

 Write end 
#include<unistd.h>
#include<string.h>
#include<sys/shm.h>
#include<stdio.h>
#define IPC_KEY 0x12345678
int main(){
  //1. Create shared memory 
  //int shmget( identifier , size , Sign a | jurisdiction )
  int shm_id=shmget(IPC_KEY,32,IPC_CREAT|0664);
  if(shm_id<0){
    perror("shmget error");
    return -1;
  }

  //2. Establish a mapping relationship 
  //shmat( Operation handle , Mapping first address , Operating authority );
  void *shm_start=shmat(shm_id,NULL,0);
  if(shm_start==(void*)-1){
    perror("shmat error");
    return -1;
  }

  //3. Perform memory operations 
  int i=0;
    while(1){
      snprintf(shm_start,"%s+%d"," It's raining again ~",i++);
      sleep(1);

    }
  //4. Unmapping 
  shmdt(shm_start);
  //5. Delete shared memory 
  shmctl(shm_id,IPC_RMID,NULL);
  return 0;
}
 Reading end 
#include<unistd.h>
#include<string.h>
#include<sys/shm.h>
#include<stdio.h>
#define IPC_KEY 0x12345678
int main(){
  //1. Create shared memory 
  //int shmget( identifier , size , Sign a | jurisdiction )
  int shm_id=shmget(IPC_KEY,32,IPC_CREAT|0664);
  if(shm_id<0){
    perror("shmget error");
    return -1;
  }

  //2. Establish a mapping relationship 
  //shmat( Operation handle , Mapping first address , Operating authority );
  void *shm_start=shmat(shm_id,NULL,0);
  if(shm_start==(void*)-1){
    perror("shmat error");
    return -1;
  }

  //3. Perform memory operations 
  while(1){
    sleep(1);
    printf("%s\n",shm_start);

  }
  //4. Unmapping 
  shmdt(shm_start);
  //5. Delete shared memory 
  shmctl(shm_id,IPC_RMID,NULL);
  return 0;
}

3、 ... and . Message queue

1. The essence

A priority queue created in the kernel ; Having an identifier can be found by other processes , Multiple processes access the same queue , Communication is achieved by adding or acquiring nodes

2. Communication principle

Message queues transmit data nodes

The node contains two messages :1. type : Used to distinguish identity  2. data

3. characteristic

(1) Duplex communication (2) It comes with synchronization and mutual exclusion (3) Life cycle changes with kernel (4) The kernel controls its size , There's a size limit

Four . Semaphore

1. The essence

A semaphore is essentially a counter in the kernel

effect : Realize the synchronization and mutual exclusion between processes ( Protect inter process access to critical resources )

2. The principle of semaphore synchronization and mutual exclusion

Synchronization : Initialize the counter according to the number of resources

Count resources through counters , If the count is greater than 0 It means that the resource can be accessed , If the resource is less than or equal to 0 It means that... Cannot be accessed , Block the process

P operation : Before the process accesses the resource , Determine whether the count is greater than 0;

          Greater than 0, Then return to , Count -1; If less than 0, Blocking process , Count -1;

V operation : When a new resource is generated , Count +1, Wake up a blocked process

Achieve mutual exclusion :

Initialize critical resource counter to 1;

Before accessing critical resources P operation , After accessing critical resources V operation . Achieve unique access

原网站

版权声明
本文为[Exy-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130620441441.html