There are 4 ways to communicate between linux processes:
(1) Pipeline
(2) message queue message queue
(3) shared memory share memory
(4) Network socket socket
Pipe is a message passing mechanism provided by the Linux operating system.
In linux, many things are abstracted into files, which abstracts all devices into files. To operate this file is to operate the device.
Interprocess communication is a new file type, pipe. Not an ordinary file.
Next, the pipeline communication process is described as follows:
1. Create a pipe folder
mkdir pipe
2.mkfifo ~/project/message
cd pipe
pipe message #Create a pipe
A pipe object is created, open the pipe file in process A, write data to the file, and in process B, open the pipe file and read data from the file. So the data is passed from process A to process B. Obviously, the pipe file is not ordinary document.
3. Create the write.cpp file
touch write.cpp
content:
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> intmain() { int fd=open("message",O_WRONLY); if(fd<0) { printf("failed to open pipe\n"); return -1; } printf("open ok.\n"); char data[12]="hello"; write(fd,data,5); printf("press enter to exit..\n"); getchar(); close(fd); return 0; }
4. Create read.cpp file
touch read.cpp
content:
#include<unistd.h> #include<fcntl.h> #include<iostream> #include<stdio.h> intmain() { int fd=open("message",O_RDONLY); if(fd<0) { printf("failed to open pipe!\n"); return -1; } printf("open ok.\n"); char data[12]; int n=read(fd,data,12); printf("get %d bytes\n",n); printf("press enter to exit..\n"); getchar(); close(fd); return 0; }
5. Open a terminal and compile write.cpp to generate the executable file write
g++ write.cpp -o write
6. Open another terminal to compile read.cpp and generate the executable file read
g++ read.cpp -o read
7. Execute write
./write
8. Execute read
./read
Results of the: