有名管道(FIFO)

发布时间 2023-04-29 09:43:17作者: WTSRUVF

# 父子进程之间示例

/*
    有名管道(FIFO)
        提供一个路径名与之关联,以FIFO的文件形式存在于文件系统中
        读写操作和普通文件一样,常用于不存在关系的进程之间

    注意事项:
        读写进程只要有一端未打开,另一打开的一端就会阻塞在read或write处
        当两端都打开,其中一端关闭时,另一端也停止

    通过命令创建有名管道
        mkfifo 名字
    
    通过函数创建有名管道
        #include <sys/types.h>
        #include <sys/stat.h>

        int mkfifo(const char *pathname, mode_t mode);
            参数:
                pathname:路径
                mode:权限,和open一样,八进制
            返回值:
                成功:0
                失败:-1

*/


// 父子进程之间
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{

    if(access("fifo1", F_OK) == 0)
    {
        remove("fifo1");

    }


    int mkfifo_flag = mkfifo("fifo1", 0777);

    if(mkfifo_flag == -1)
    {
        perror("mkfifo");
        exit(-1);
    }
    int fifofd = open("fifo1", O_RDWR);

    int fork_flag = fork();
    if(fork_flag == 0)
    {
        char str[1024];
        strcpy(str, "Hello World");

        write(fifofd, str, strlen(str));
    }
    else
    {
        char str[1024];
        read(fifofd, str, sizeof(str));

        printf("parent recv a info : %s \n", str);


    }





}

 

# 无关联进程之间示例

write.c

// 无关系进程之间
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{

    if(access("fifo1", F_OK) == 0)
    {
        remove("fifo1");

    }


    int mkfifo_flag = mkfifo("fifo1", 0777);

    if(mkfifo_flag == -1)
    {
        perror("mkfifo");
        exit(-1);
    }
    int fifofd = open("fifo1", O_WRONLY);

    for(int i = 0; i < 10; i++)
    {
        char str[1024];
        sprintf(str, "Hello : %d", i);
        write(fifofd, str, strlen(str));
        sleep(1);
    }
    close(fifofd);


    return 0;


}

 

read.c

// 无关系进程之间
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{

    // if(access("fifo1", F_OK) == 0)
    // {
    //     remove("fifo1");

    // }


    // int mkfifo_flag = mkfifo("fifo1", 0777);

    // if(mkfifo_flag == -1)
    // {
    //     perror("mkfifo");
    //     exit(-1);
    // }
    int fifofd = open("fifo1", O_RDONLY);

    while(1)
    {
        char str[1024] = {0};  //读端接收字符串初始化为0,可防止输出乱码
        int len = read(fifofd, str, sizeof(str)); // 写端关闭时,len == 0
        if(len == 0)
        {
            printf("写端断开连接了......\n");
            break;
        }
        printf("read file recve a info : %s\n", str);
    }
    close(fifofd);







    
    return 0;


}