当前位置:网站首页>Anonymous pipeline for interprocess communication
Anonymous pipeline for interprocess communication
2022-06-30 04:14:00 【*insist】
Interprocess communication
List of articles
Interprocess communication - 1.1 The concept of interprocess communication
- 1.2 The purpose of interprocess communication
- 1.3 How to communicate between processes
- 2.1 The concept of pipes
- 2.2 Introduction to anonymous pipeline
- 2.2.1 Of the pipe 5 Species characteristics 4 In this case
- 2.3 Description of rules for pipeline reading and writing
- 4 An analysis of the situation :
- The first one is :( Son or father ) No write,( Parent or child ) always read,read Blocking
- The second kind :( Son or father ) No read ,( Parent or child ) always write,write Blocking
- The third kind of :.write Close after writing ,read The return value is 0
- A fourth :read close , Keep writing , The writer will be killed by the operating system , Writing is meaningless
- Points of attention ( a key ):
1.1 The concept of interprocess communication
Interprocess communication is the exchange and dissemination of information between processes
A very important sentence : The essence of interprocess communication is to let different processes see the same root resource 
1.2 The purpose of interprocess communication
- The data transfer : A process needs to send its own data to other processes
- Resource sharing : Multiple processes share the same resources
- Notification event : A process needs to send a message to a process , Notify it ( they ) Something happened ( If you want to notify the parent process when the process terminates )
- Process control : Some processes want full control over the execution of another process ( Such as debug process ), At this time, the control process wants to be able to intercept all traps and exceptions of another process , And can know its state change in time
1.3 How to communicate between processes
- The Conduit ( This article is about )
- Anonymous pipeline pipe
- name pipes
- System V Interprocess communication ( This article does not cover )
- System V Message queue
- System V Shared memory
- System V Semaphore
- POSIX Interprocess communication ( This article does not cover )
- Message queue
- Shared memory
- Semaphore
- The mutex
- Condition variables,
- Read-write lock
2.1 The concept of pipes
Pipeline is an ancient form of interprocess communication
- A data stream that connects one process to another process is usually called a “ The Conduit ”
2.2 Introduction to anonymous pipeline
An anonymous pipeline is a pipeline without a name , By function pipe(int fd[2]) establish , It is often used to communicate between processes with kinship , As a resource shared by two processes , So as to realize the information exchange between the two processes and achieve the purpose of communication .
2.2.1 Of the pipe 5 Species characteristics 4 In this case
5 Species characteristics :
1. Synchronization and mutual exclusion mechanisms have been automatically provided inside the pipeline ( Read and write can only wait for one another , It can't be done at the same time )
2. If the process of opening the file exits , Files will also be released ( All processes that have opened a file exit , The resources of this file will be completely released )
3. Pipelines provide streaming services ( This article only mentions , Just know that there is such a thing , Follow up blogs should say )
4. The pipeline is half duplex communication ( Pipes can only be One-way communication Of , For example, the parent process is writing data to an anonymous pipeline , Then the subprocess cannot read the pipeline information , You cannot read until the parent process has finished writing , That is, the parent-child process can only be one of them to read or write to the pipeline , A parent-child process cannot read or write to a pipeline at the same time !!!)
5. Anonymous pipes are suitable for interprocess communication between blood related processes , Often used for father and son
4 In this case :
- 1.( Son or father ) No write,( Parent or child ) always read,read Blocking
- 2.( Son or father ) No read ,( Parent or child ) always write,write Blocking
- 3.write Close after writing ,read The return value is 0
- read close , Keep writing , The writer will be killed by the operating system , Writing is meaningless
2.3 Description of rules for pipeline reading and writing
(fd_arrray[3] fd_array[4] The third picture that I don't understand has an explanation )

adopt pipe(int fd[2]) After creating the pipe , Re pass fork() Create child process
Wrong reading and writing :
Read and write correctly :

The parent process reads , Related code written by child process ( The main code of this article , The example is also transformed from this code ):
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd[2];
if(pipe(fd)<0)
{
// Create pipes
perror("pipe!");// This function has its own line feed
return 1;
}
//printf("fd[0]\n",fd[0]);
//printf("fd[1]\n",fd1]);
// Create child process
pid_t id = fork();
if(id==0)
{
//child
// What the subprocess needs to do is write data to the pipeline Turn off the reader Finally, close the writing end after writing
close(fd[0]);
int count=10;
const char* str="hello father i am your child!\n";
while(count)
{
write(fd[1],str,strlen(str));
// printf("%s",str);
count--;
sleep(1);
}
close(fd[1]);
exit(1);
}
else if(id>0)
{
//father
close(fd[1]);// The parent process closes the write side , Read only
char buff[64];
while(1)
{
int ret=read(fd[0],buff,sizeof(buff));
if(ret>0)
{
buff[ret]='\0';
printf("child send to father's message is:%s\n",buff);
// close(fd[0]);
// break;
// You can't just break Otherwise, it is read only once It's written here 10 Keep reading Don't stop until you read the end of the file To finish reading
}
else if(ret==0)
{
printf("read file of end!\n");
break;
}
else
{
perror("read");
break;
}
}
}
else
{
//error
perror("fork!");
return 1;
}
int status=0;
int ret=waitpid(id,&status,0);// Block wait
if(ret>0)
{
printf("child is quit! single is:%d",status&0x7F);
}
return 0;
}
4 An analysis of the situation :
The first one is :( Son or father ) No write,( Parent or child ) always read,read Blocking

Code :
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd[2];
int ret = pipe(fd);
if(ret<0)
{
perror("pipe");
return -1;
}
pid_t id=fork();// Create child process
if(id==0)
{
//child
close(fd[0]);// The subprocess closes the reader So that it can only write to the pipeline
const char* str="i\n";
int count=5;
while(count)
{
if(count>=2)//count Greater than or equal to 2 Just write Or sleep
{
write(fd[1],str,strlen(str));
count--;
sleep(1);
}
else{
sleep(1000);// The subprocess will not be written after being written twice Sleep But the parent process keeps reading This will create a read jam
}
}
// Keep writing When no longer printing count The buffer of the pipeline is full , At this time count Is the capacity of the pipe
}
else if(id>0)
{
//father
close(fd[1]);// Close the write end
// sleep(1000);
char arr[1000];
while(1)
{
int ret=read(fd[0],arr,sizeof(arr));
if(ret>0)// Read the content
{
arr[ret]='\0';
printf("%s",arr);
}
else if(ret==0)
{
// Read the end of the file
printf("read end of file!\n");
break;
}
else
{
//read error
// perror("read");
printf("read error!\n");
break;
}
}
}
else
{
//error
perror("fork!");
}
int status=0;
int s=waitpid(id,&status,0);// Block wait
if(s>0)
{
printf("child quit!\n");
}
else
{
printf("wait error!");
}
printf("quit singal is:%d\n",ret&0x7F);
return 0;
}
The second kind :( Son or father ) No read ,( Parent or child ) always write,write Blocking

Code :
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd[2];
int ret = pipe(fd);
if(ret<0)
{
perror("pipe");
return -1;
}
pid_t id=fork();// Create child process
if(id==0)
{
//child
close(fd[0]);// The subprocess closes the reader So that it can only write to the pipeline
const char* str="i";// Write one byte at a time
int count=0;
while(1)
{
write(fd[1],str,strlen(str));
count++;
printf("%d\n",count);// Write once, print once count
}
// Keep writing When no longer printing count The buffer of the pipeline is full , At this time count Is the capacity of the pipe
}
else if(id>0)
{
//father
close(fd[1]);// Close the write end
sleep(1000);// Let the parent process sleep directly , Will not read the data in the pipeline , Just keep the subprocess writing in
char arr[1000];
while(1)
{
int ret=read(fd[1],arr,sizeof(arr));
while(1)
{
if(ret>0)// Read the content
{
arr[ret]='\0';
printf("%s",arr);
}
else if(ret==0)
{
// Read the end of the file
printf("read end of file!\n");
break;
}
else
{
//read error
perror("read");
break;
}
}
}
}
else
{
//error
perror("fork!");
}
// Wait for the subprocess to exit
int status=0;
int s=waitpid(id,&status,0);// Block wait
if(s>0)
{
printf("child quit!\n");
}
else
{
printf("wait error!");
}
printf("quit singal is:%d\n",ret&0x7F);
return 0;
}

Running results -> No more printing count explain write blocked Measured pipe The buffer size is 65536 Bytes
Combined with documentation This machine is 3. Several versions of So it is 65536 Bytes To be confirmed

The third kind of :.write Close after writing ,read The return value is 0
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd[2];
int ret = pipe(fd);
if(ret<0)
{
perror("pipe");
return -1;
}
pid_t id=fork();// Create child process
if(id==0)
{
//child
close(fd[0]);// The subprocess closes the reader So that it can only write to the pipeline
const char* str="i\n";// Write one byte at a time
int count=5;
while(count)
{
write(fd[1],str,strlen(str));
count--;
sleep(1);
}
// a key
close(fd[1]);// Close after writing Write end When the parent process reads, it will read to the end of the file The return value is 0
exit(0);// The subprocess exits after writing
}
else if(id>0)
{
//father
close(fd[1]);// Close the write end
// sleep(1000);
char arr[1000];
while(1)
{
int ret=read(fd[0],arr,sizeof(arr));
if(ret>0)// Read the content
{
arr[ret]='\0';
printf("%s",arr);
}
else if(ret==0)
{
// Read the end of the file
printf("read end of file!\n");
break;
}
else
{
//read error
// perror("read");
printf("read error!\n");
break;
}
}
int status=0;
int s=waitpid(id,&status,0);// Block wait
if(s>=0)
{
printf("child quit!\n");
}
else
{
printf("wait error! s:%d\n",s);
}
printf("quit singal is:%d\n",status&0x7F);
return 0;
}
else
{
//error
perror("fork!");
}
return 0;
}
Running results : The write end is closed after writing Read end reread Read to the end of the file read The return value is 0

A fourth :read close , Keep writing , The writer will be killed by the operating system , Writing is meaningless
Code :
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd[2];
int ret = pipe(fd);
if(ret<0)
{
perror("pipe");
return -1;
}
pid_t id=fork();// Create child process
if(id==0)
{
//child
close(fd[0]);// The subprocess closes the reader So that it can only write to the pipeline
const char* str="i\n";// Write one byte at a time
while(1)
{
write(fd[1],str,strlen(str));
sleep(1);
}
close(fd[1]);// Close after writing Write end When the parent process reads, it will read to the end of the file The return value is 0
exit(0);
}
else if(id>0)
{
//father
close(fd[1]);// Close the write end
close(fd[0]);// The parent process closes the reader directly Do not read pipeline information The subprocess is still writing It makes no sense The operating system will kill it
// sleep(1000);
char arr[1000];
while(1)
{
int ret=read(fd[0],arr,sizeof(arr));
if(ret>0)// Read the content
{
arr[ret]='\0';
printf("%s",arr);
}
else if(ret==0)
{
// Read the end of the file
printf("read end of file!\n");
break;
}
else
{
//read error
// perror("read");
printf("read error!\n");
break;
}
}
int status=0;
int s=waitpid(id,&status,0);// Block wait
if(s>=0)
{
printf("child quit!\n");
}
else
{
printf("wait error! s:%d\n",s);
}
printf("quit singal is:%d\n",status&0x7F);
return 0;
}
else
{
//error
perror("fork!");
}
return 0;
}
Running results : The child process is killed by the operating system Because the parent process cannot read The subprocess is meaningless And the subprocess exit signal is 13 SINPIPE

Points of attention ( a key ):
1.pipe() The created pipeline is to pass an array with two elements fd[0] f[1] Represents the read and write side respectively
2. Since the read or write end of the parent-child process should be turned off after the child process is created , So why not open the read / write side of the parent process at the beginning of creation ?
In essence, it is to let the child process inherit , Turn off the back end , Because the pipeline can only communicate in one direction
3. The pipeline has its own synchronization and mutual exclusion mechanism , This prevents the parent and child processes from using the same resource at the same time , When the child process writes, the parent process cannot read , You can only read after the subprocess has finished writing , That is, reading and writing cannot be carried out at the same time , Otherwise, the data will be disordered . Under multi execution flow ( Father and son ) The same resource you see is called Critical resources
4 If the write end is off , The reader will read to the end of the file , return 0, On behalf of the end of the document
5. The life cycle of a file ends with the end of the process , That is, the process of opening the file exits , The file will also be released , Here, it may be that multiple processes have opened a file , Then all processes that open the file will exit the file resource before it is completely released
6. The pipeline provides streaming services and the pipeline is half duplex communication
7. Anonymous pipes are suitable for interprocess communication between blood related processes , Often used for father and son
边栏推荐
- Pytorch Profiler+ Tensorboard + VS Code
- Day 11 script and game AI
- Indefinite parameters of JS function
- idea灰屏问题
- 绿色新动力,算力“零”负担——JASMINER X4系列火爆热销中
- Use ideal to connect to the database. The results show some warnings. How to deal with this part
- Unity échappe à l'entrée de caractères lors de l'entrée de chaînes dans l'éditeur
- Modifier of JS regular expression
- AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
- Clients accessing the daytime service (TCP)
猜你喜欢

NER中BiLSTM-CRF解读score_sentence

(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces

《机器人SLAM导航核心技术与实战》第1季:第0章_SLAM发展综述

【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码

进程间通信之匿名管道

RPC correction

Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview
![[note] on May 27, 2022, MySQL is operated through pychart](/img/34/36a3765683b2af485ca7c3e366da59.png)
[note] on May 27, 2022, MySQL is operated through pychart

Share an example of a simple MapReduce method using a virtual machine

El upload upload file (manual upload, automatic upload, upload progress)
随机推荐
I get n offers in two months. I don't have any difficult interviewers here
Idea grey screen problem
Huawei cloud native - data development and datafactory
Hebb and delta learning rules
Jour 9 Gestion des scripts et des ressources
I spent three years in a big factory outsourcing, which subverted my understanding!
[operation] write CSV to database on May 28, 2022
第十天 数据的保存与加载
The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure
Day 10 data saving and loading
EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
2021-11-04
Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
Do280 private warehouse persistent storage and chapter experiment
Titanic(POJ2361)
Es2019 key summary
matplotlib. pyplot. Hist parameter introduction
网络层详解
各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
[note] on May 28, 2022, data is obtained from the web page and written into the database