Linux learning summary (11) IPC method-named pipe FIFO

FIFO

      FIFO is often referred to as a named pipe to distinguish pipes. Pipes can only be used between "blood-related" processes, but through FIFO, unrelated processes can also exchange data.
      FIFO is one of the basic file types in Linux. However, FIFO files have no data blocks on the disk, and are only used to identify a channel in the kernel. Each process can open this file for read/write, which is actually reading and writing the kernel channel. , In this way, inter-process communication is realized.

Usage:
Command: mkfifo pipe name
Library function: int mkfifo(const char *pathname, mode_t mode); return 0 on success, return -1 on failure.
Once a FIFO is created with mkfifo, you can use open to open it, common files I /O functions can be used in fifo, such as: close, read, write, unlink, etc.

Create myfifo named pipe file
Insert picture description here
Writer:

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

void sys_err(char *str)
{
    
    
    perror(str);
    exit(-1);
}

int main(int argc, char *argv[])
{
    
    
    int fd, i;
    char buf[4096];

    if (argc < 2) {
    
    
        printf("Enter like this: ./a.out fifoname\n");
        return -1;
    }
    fd = open(argv[1], O_WRONLY);
    if (fd < 0) 
        sys_err("open");

    i = 0;
    while (1) {
    
    
        sprintf(buf, "hello itcast %d\n", i++);

        write(fd, buf, strlen(buf));
        sleep(1);
    }
    close(fd);
    return 0;
}

Reading end:

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

void sys_err(char *str)
{
    
    
    perror(str);
    exit(1);
}

int main(int argc, char *argv[])
{
    
    
    int fd, len;
    char buf[4096];

    if (argc < 2) {
    
    
        printf("./a.out fifoname\n");
        return -1;
    }
    fd = open(argv[1], O_RDONLY);
    if (fd < 0) 
        sys_err("open");
    while (1) {
    
    
        len = read(fd, buf, sizeof(buf));
        write(STDOUT_FILENO, buf, len);
        sleep(3);           //多个读端时应增加睡眠秒数,放大效果.
    }
    close(fd);

    return 0;
}

Guess you like

Origin blog.csdn.net/bureau123/article/details/112272353