Linux学习总结(十一)IPC方法-命名管道FIFO

FIFO

      FIFO常被成为命名管道,以区分管道(pipe),管道(pipe)只能用于“有血缘关系”的进程间,但通过FIFO,不相关的进程也能交换数据。
      FIFO是Linux基础文件类型中的一种,但是,FIFO文件在磁盘上没有数据块,仅仅用来标识内核中一条通道,各进程可以打开这个文件进行read/write,实际上是在读写内核通道,这样就实现了进程间通信。

使用方式:
命令:mkfifo 管道名
库函数:int mkfifo(const char *pathname, mode_t mode);成功返回0,失败返回-1
一旦使用mkfifo创建了一个FIFO,就可以使用open打开它,常见的文件I/O函数都可用于fifo,如:close,read,write,unlink等。

创建myfifo命名管道文件
在这里插入图片描述
写端:

#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;
}

读端:

#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;
}

猜你喜欢

转载自blog.csdn.net/bureau123/article/details/112272353