当前位置:网站首页>Named pipes for interprocess communication
Named pipes for interprocess communication
2022-06-30 04:14:00 【*insist】
List of articles
- 1.1 name pipes
- 2.1 Through interprocess communication, the string sent by the client is converted into a command to be executed by the server
- 3.1 Design a calculator by transferring data through interprocess communication
- 4.1 Inter process file transfer is realized through inter process communication
1.1 name pipes
Question elicitation : Why do you need to name pipes when you have anonymous pipes ?
Because anonymous pipes are only used for those who are related , For example, anonymous pipes can be used for communication between parent and child processes , But if you want to make two unrelated processes communicate , Anonymous channels are useless , You need to use named pipes to implement . Named pipes are a special kind of file , It enables processes to share the same resource , Communication is realized by reading and writing the resource . Named pipes remove the restriction that pipes can only be used between related processes .
1.2 The creation of named pipes
The first one is : Create from the command line
mkfifo +" file name " The way
The second kind : By code ( Call function mkfifo() ) establish
Definition :
The first parameter is the path of the pipeline file to be created ( Name under the current path ), The second parameter is permission setting It's usually 0xxx In the form of
Return value : If the creation is successful, return 0 Unsuccessful return -1 This can be used to determine whether the creation is successful
example :
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
if(makfifo("myfifo",0644)<0)
{
printf("mkfifo fail!\n");
return -1;
}
return 0;
}
1.3 The difference between named pipes and anonymous pipes
- Named pipes by mkfifo Function creation , Open with open
- Anonymous channels are made up of pipe Create and open
- The only difference between named pipes and anonymous pipes is the way they are created and opened , After creation and opening, they have the same semantics
Read only open with open(“ file name ”,O_RDONLY);
Write only for opening open(“ file name ”,O_WRONLY);
Open and O_CREAT
To implement different opening methods , Use or | Mix the above
Code demonstration ( Use named pipes to realize interprocess communication )
// Two .c file client.c serve.c One acts as a client One acts as a server Reference the same header file serve.h
//serve.h
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#define File_Name "fifo"
-----------------------------------
//serve.c
#include"sever.h"
int main()
{
if(mkfifo(File_Name,0644)<0)
{
perror("mkfifo");
return -1;
}
// adopt mkfifo Created named pipe Next, let the server communicate with the client through the pipeline
// The next step is to realize the communication between the two processes by reading and writing the tube
int fd = open(File_Name,O_RDONLY);// Open file read-only
if(fd < 0)
{
perror("open");
return -2;
}
char srt[128];
while(1)
{
srt[0]=0;// Empty files
int s= read(fd,srt,sizeof(srt));//open The first parameter of is the filename and read The first parameter of is the file descriptor
if(s>0)// I haven't finished reading
{
srt[s-1]=0;// If I read 127 Bytes will be returned 127 Change the subscript to 0 Print out what you read Read is read s individual Which includes \n And then put s-1 Corresponding \n Set to 0
printf("client send message# %s\n",srt);
}
else if(s==0)
{
printf("client quit!\n");
break;
}
else
{
// Description read error The return is -1
perror("read");
break;
}
}
close(fd);// Open the file and close it at last
return 0;
}
----------------------------------------
//client.c
#include"serve.h"
int main()
{
// Open the pipe file first
int fd=open(File_Name,O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
// After opening the file, read the data from the keyboard Then write the read data into the pipeline
char msg[128];
while(1)
{
msg[0]=0;
printf("please Enter# ");
fflush(stdout);// The above print did not bring back the car Full buffer So you need to manually refresh the buffer
int ret=read(0,msg,sizeof(msg)-1);
if(ret>0)
{
msg[ret]=0;
write(fd,msg,strlen(msg));
}
}
close(fd);
return 0;
}
2.1 Through interprocess communication, the string sent by the client is converted into a command to be executed by the server
Code :( Only the code of the server is changed , Is to create a subprocess Then replace... With a process Execute the characters sent by the client as commands Only very small changes )
#include"serve.h"
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
if(mkfifo(File_Name,0644)<0)
{
perror("mkfifo");
return -1;
}
// adopt mkfifo Created named pipe Next, let the server communicate with the client through the pipeline
// The next step is to realize the communication between the two processes by reading and writing the tube
int fd = open(File_Name,O_RDONLY);// Open file read-only
if(fd < 0)
{
perror("open");
return -2;
}
char srt[128];
while(1)
{
srt[0]=0;// Empty files
int s= read(fd,srt,sizeof(srt));//open The first parameter of is the filename and read The first parameter of is the file descriptor
if(s>0)// I haven't finished reading
{
srt[s-1]=0;// If I read 127 Bytes will be returned 127 Change the subscript to 0 Print out what you read Read is read s individual Which includes \n And then put s-1 Corresponding \n Set to 0
// printf("client send message# %s\n",srt);
printf("client send command/message# %s\n",srt);
fflush(stdout);
// Places of change /
int pid = fork();// Create a child process to complete the input command
if(pid==0)
{
//child
execlp(srt,srt,NULL);// Process replacement
exit(1);// Subprocess exit
}
waitpid(pid,NULL,0);// Blocking wait for child process to exit
}
else if(s==0)
{
printf("client quit!\n");
break;
}
else
{
// Description read error The return is -1
perror("read");
break;
}
}
close(fd);// Open the file and close it at last
return 0;
}
Add :
The interprocess communication here is realized through pipeline The data is disk free That is to say, the data has not been flushed to the disk , It's in memory !!!!
3.1 Design a calculator by transferring data through interprocess communication
Code :( Only the server has been changed )
#include"serve.h"
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
if(mkfifo(File_Name,0644)<0)
{
perror("mkfifo");
return -1;
}
// adopt mkfifo Created named pipe Next, let the server communicate with the client through the pipeline
// The next step is to realize the communication between the two processes by reading and writing the tube
int fd = open(File_Name,O_RDONLY);// Open file read-only
if(fd < 0)
{
perror("open");
return -2;
}
char srt[128];
while(1)
{
srt[0]=0;// Empty files
int s= read(fd,srt,sizeof(srt));//open The first parameter of is the filename and read The first parameter of is the file descriptor
if(s>0)// I haven't finished reading
{
srt[s-1]=0;// If I read 127 Bytes will be returned 127 Change the subscript to 0 Print out what you read Read is read s individual Which includes \n And then put s-1 Corresponding \n Set to 0
printf("client send message# %s\n",srt);
char* st=srt;
int flag=0;
while(*st)// Find the operation symbol
{
switch(*st)
{
case'+':
flag=1;
break;
case'-':
flag=2;
break;
case'*':
flag=3;
break;
case'/':
flag=4;
break;
case'%':
flag=5;
break;
}
st++;
}
int a,b,c;
const char* str=" +-*/%";
if(flag)// If the operation symbol is found, disassemble the molecular string
{
char* s1=strtok(srt,str);
char* s2=strtok(NULL,str);
a=atoi(s1);// Character to number
b=atoi(s2);
switch(flag)// Calculation
{
case 1:
c=a+b;
break;
case 2:
c=a-b;
break;
case 3:
c=a*b;
break;
case 4:
c=a/b;
break;
case 5:
c=a%b;
break;
}
printf("%d %c %d = %d\n",a,str[flag],b,c);// Print
}
}
else if(s==0)
{
printf("client quit!\n");
break;
}
else
{
// Description read error The return is -1
perror("read");
break;
}
}
close(fd);// Open the file and close it at last
return 0;
}
4.1 Inter process file transfer is realized through inter process communication
Code :
// client
#include"serve.h"
int main()
{
// Open the pipe file first
int fd=open(File_Name,O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
int fd1=open("file.txt",O_RDONLY);// Open file Read... From the pipe file.txt The data of Go back to file-bk.txt You can copy files by writing them inside
if(fd1<0)
{
perror("open file.txt");
return -2;
}
// After opening the file, read the data from the keyboard Then write the read data into the pipeline
char msg[128];
while(1)
{
msg[0]=0;
dup2(fd1,0);// Redirect fd by 0 That is to say, it is equivalent to stdin Shut down To create a file-bk To read data from standard input is to read data from file-bk Read in data
ssize_t ret=read(0,msg,sizeof(msg));
if(ret==sizeof(msg))
{
// msg[ret-1]=0;// Set up \0 So that the file can end when it is output
write(fd,msg,ret);// Write the data to the newly opened file
}
else if(ret<sizeof(msg))
{
write(fd,msg,ret);// Write data that is less than the expected size to a file
printf("read end of file!\n");
break;
}
else{
printf("read error!\n");
break;
}
}
close(fd);
close(fd1);
return 0;
}
// Server side
#include"serve.h"
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
if(mkfifo(File_Name,0644)<0)
{
perror("mkfifo");
return -1;
}
// adopt mkfifo Created named pipe Next, let the server communicate with the client through the pipeline
// The next step is to realize the communication between the two processes by reading and writing the tube
int fd = open(File_Name,O_RDONLY);// Open file read-only
if(fd < 0)
{
perror("open");
return -2;
}
int fd1=open("file-bk.txt",O_CREAT|O_WRONLY,0644);// Open an existing in read-only mode file.txt file It must be openable Don't judge
char srt[128];
while(1)
{
srt[0]=0;
int s= read(fd,srt,sizeof(srt));//open The first parameter of is the filename and read The first parameter of is the file descriptor
if(s>0)// I haven't finished reading
{
// write(fd1,srt,sizeof(srt));
write(fd1,srt,s);// No sizeof(srt)
}
else if(s==0)
{
printf("client quit!\n");
break;
}
else
{
// Description read error The return is -1
perror("read");
break;
}
}
close(fd);// Open the file and close it at last
close(fd1);
return 0;
}
summary
summary : A named pipe is actually a file , It's just that the operating system processes it , Make it have specific functions , This pipeline file is shared between unrelated processes , So that unrelated processes can see the same resource , The process reads and writes files to this resource , Realize the interaction of information , Achieve the effect of communication !!!( Once the named pipe is created , The next operation is to read and write the file )
边栏推荐
- win10系统使用浏览器下载后,内容无故移动或删除
- [summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
- 尝试链接数据库时出现链接超时报错,如何解决?
- Es2016 key summary
- 数据链路层详解
- Titanic(POJ2361)
- Pytorch Profiler+ Tensorboard + VS Code
- [note] Introduction to data analysis on June 7, 2022
- Radiant energy, irradiance and radiance
- [note] on May 28, 2022, data is obtained from the web page and written into the database
猜你喜欢
(04). Net Maui actual MVVM
Interview topic of MySQL
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
Solve the problem of Navicat connecting to the database
如何利用FME 创建自己的功能软件
Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
Interpretation score of bilstm-crf in NER_ sentence
EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
技术分享| 融合调度中的广播功能设计
Day 9 script and resource management
随机推荐
Radiant energy, irradiance and radiance
GIS related data
The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database
Collinearity problem
声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
I spent three years in a big factory outsourcing, which subverted my understanding!
JS file block to Base64 text
网络层详解
Introduction to cloud native + container concept
JS reflect
Node red series (28): communication with Siemens PLC based on OPC UA node
JS import and export
如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
Educoder group purchase suspension box page production
RPC correction based on arcpy API
如何利用FME 创建自己的功能软件
Machine learning notes
Error in conditional filter (if) syntax in sum function in SQL Server2005
Interface testing -- how to analyze an interface?