IPC (two) ---------named pipe (FIFO)

1. Introduction to FIFO

    1、API:

          #include <sys/types.h>

         #include <sys/stat.h>

        int mkfifo(const char * pathname,mode_t mode);

       Return: Return 0 for success, -1 for error

   2、

      FIFO can be used to communicate between any processes (processes that are related or okay) as long as they have appropriate access rights.

      The essence is a cache in the kernel. In addition, it exists as a special device file (pipe file) in the file system. There is only one index block in the file system to store the file path, and the data block is in the kernel.

      The named pipe FIFO must be opened for reading and writing at the same time, writing or reading alone will cause blocking.

      The command mkfifo can also create named pipes.

      The operation of FIFO is the same as that of ordinary files. APIs such as open, close, read, write, and unlink are all available.

 

Second, the code example

     Create a pipe through the external mkfifo, and use the name of the pipe as the parameter of the main function of the two processes to complete the read and write communication in the two processes.

    fifo_read.c

  

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


int main(int argc,char *argv[])
{

    if(argc < 2)
    {
        printf("usage: a.out fifoname\n");

        exit(-1);
    }


    printf("open fifo:\n");
    int fd = open(argv[1],O_RDONLY);

    if(fd < 0)
    {
        printf("fifo open error\n");

        exit(-1);
    }
    else
    {
        printf("fifo open succcess:%d\n",fd);
    
           
        char buf[256] = {0};

        while(read(fd,buf,sizeof(buf)) > 0)
        {
        
            printf("%s",buf);

            memset(buf,0,sizeof(buf));
        }


    }
    close(fd);

    exit(0);

}   

   fifo_write.c

 

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <string.h>
 #include <unistd.h>


int main(int argc,char*argv[])
{
    if(argc < 2)
    {
        printf("usage: ./a.out mkfifo\n");
        exit(-1);
    }


    printf("open fifo :\n");
    int fd = open(argv[1],O_WRONLY);
    
    if(fd < 0)
    {
        printf("fifo open error\n");

        exit(-1);
    }
    else
    {
        printf("fifo open success:%d\n",fd);


        char *str = "abcdefghijklmnopqrstuvwxyz";

        write(fd,str,strlen(str));
        
        close(fd);
    }





    exit(0);

}

Create a pipeline com.pipe and pass parameters to the two processes

 

 

Guess you like

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