Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to realize Pipeline Communication in Linux

Shulou Source: shulou.com Published: 2022-06-01 18:55:09 09月16日 Update

How to achieve pipeline communication in Linux, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, people who have this need can learn, I hope you can gain something.

I. Definitions

The pipeline is one-way, first-in, first-out. It connects the input of one program to the output of another. After the data is read by a process, it is deleted from the pipeline. It is divided into nameless and famous pipes. The former is used for communication between parent and child processes, while the latter is used for communication between two processes in the same system.

II. Unnamed pipeline

The code is as follows:

int pipe(int fd[2]);

Where fd[0] is used to read pipes and fd[1] is used to write pipes. Returns zero if successful,-1 otherwise, error reason stored in errno.

Third, the famous pipeline: FIFO

The code is as follows:

int mkfifo(const char* pathname,mode_t mode)

Use O_NONBLOCK when open, and immediately return an error if the access requirements cannot be met. Erron is ENXIO.

Examples:

The code is as follows:

fread. c//Read files

#include

#include

#define FIFO "myfifo"

main(){

int fd;

char buff[100];

if(access(FIFO,F_OK) == -1){

mkfifo(FIFO,0777);

}

fd=open(FIFO,O_RDONLY| O_NONBLOCK); //Set non-blocking on, otherwise it will block the read function when there is no input

int num;

while(1){

memset(buff,'\0', 100); //garbled if last character is not cleared

if((num=read(fd,buff,100))==0){

printf("waiting.....\ n");

sleep(1);

continue;

}

printf("read %d in fifo , it's %s",num,buff);

sleep(1);

}

}

fwrite. c//Write a file

#include

#include

#include

#define FIFO "myfifo"

main(){

int fd;

char buff[100];

memset(buff,'\0',100);

scanf("%s",buff);

if(access(FIFO,F_OK) == -1){

mkfifo(FIFO,0777);

}

fd=open(FIFO,O_WRONLY);

int num;

num=write(fd,buff,strlen(buff));

printf("%d char is written! It's %s\n",num,buff);

}

Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.

Tags: Pipe process communication code name file program help input blocking clear success two random code example advanced content function one-way reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Huawei Shulou Technology Microsoft macOS