IPC (1) ---------Anonymous pipe

1. Classification of pipelines

          Pipes are divided into anonymous pipes and named pipes .

         Anonymous pipe :

         (1), in the relationship process (between the parent process and the child process, the sibling process)

         (2) Called by the pipe system, and the pipe is established by the parent process.

         (3) The pipeline is located in the kernel space, which is actually a cache.

        Named pipe:

        (1) Data can be transferred between any two processes through named pipes.

        (2). Created by system call mkfifo.

       (3) The essence is a cache in the kernel, and it exists as a special device file (pipe file) in the file system.

2. This article mainly talks about anonymous channels:

      Pipeline creation:

       #include <unistd.h>

       int pipe(int fd[2]);

       Return: Return 0 for success, -1 for error;

       fd[0]: read end of pipe

       fd[1]: write side for pipe

Three, pipeline creation and reading and writing code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

#include <stdlib.h>



int main()
{
    int fd[2];
    pid_t pid;



    //管道创建成功后,fd[0]是读管道,fd[1]是写管道
    if(pipe(fd) < 0)
    {
        printf("pipe error\n");

        exit(-1);
    }



    if((pid = fork())< 0)
    {
        printf("fork error\n");

        exit(-1);
    }

    if(pid == 0)//子进程
    {

        close(fd[0]);//子进程关掉读管道
        printf("child process\n");
        
        int start = 1,end = 100;

        write(fd[1],&start,sizeof(start));
        write(fd[1],&end,sizeof(end));

        exit(0);
    }
    else
    {
        printf("parent child\n");
        close(fd[1]);//父进程关掉写管道
        
        int start = 0,end = 0;

        read(fd[0],&start,sizeof(start));
        read(fd[0],&end,sizeof(end));

        printf("start=%d,end=%d\n",start,end);

        exit(0);
    
    }




    return 0;

}

operation result:

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/111662073
IPC