laitimes

Interprocess communication in linux - pipes

author:See the words like crazy

Each process has its own user address space, and the global variables between each process cannot be seen with each other, so the communication between different processes must go through the kernel, opening up a buffer in the kernel, one process copies the data from the user space to the kernel cache, and the other process takes the data away from the kernel cache, this communication mechanism is inter-process communication.

A pipeline is a method of interprocess communication, primarily for parent-child processes. That is, the communication between parent and child created through fork().

Creation of pipelines

#include<unistd.h>

Int pipe(int fd[2])

Return value: 0 returned successfully, -1 was returned for error

The Fd parameter returns descriptors for two files, fd[0] pointing to the read end of the pipe, fd[1] pointing to the pipe's write, and fd[1] output being the input to fd[0].

l Pipeline for inter-process communication

1. The parent process creates the pipeline, and gets two file descriptors pointing to both ends of the pipeline;

2. The parent process forks out the child process, and the child process also has two file descriptors pointing to the same pipe;

3. The parent process closes fd[0], the child process closes fd[1], that is, the child process closes the read end of the pipe, and the parent process closes the write end of the pipe, (the pipeline only supports one-way communication). The child process writes data to the pipeline, and the parent process reads the data from the pipeline. Pipelines are implemented in ring queues.

l Pipeline characteristics

1. The pipeline only supports parent-child process communication,

2. The pipeline only supports one-way communication;

3. The pipeline faces the byte stream;

4. The pipeline follows the process, the process is in the pipeline, the port corresponding to the process disappears the pipeline is closed, and both processes disappear the pipeline also disappears.

l Pipeline communication code

#include<stdio.h>

#include<string.h>

#include<errno.h>

int main()

{

int fd[2];

int pipe_id=pipe(fd);

if(pipe_id==-1)

perror("pipe error\n");

return -1;

}

pid_t id=fork();

if(id==0)

int i=0;

close(fd[0]);

char* child_fork="I am child fork!";

while(i<5)

write(fd[1],child_fork,strlen(child_fork)+1);

sleep(2);

i++;

else if(id>0)

close(fd[1]);

char msg[100];

int j=0;

while(j<5)

memset(msg,'\0',sizeof(msg));

ssize_t s=read(fd[0],msg,sizeof(msg));

if(s>0)

msg[s-1]='\0';

printf("%s\n",msg);

d++;

else

perror("fork error\n");

return 0;

l

Read on