命名管道

1.命名管道的创建

(1) 通过命令创建

mkfifo filename

(2)在程序中创建

int mkfifo(const char* filename, mode_t mode);
2. 命名管道和匿名管道的区别

    (1)匿名管道由pipe函数创建并且打开
    (2)命名管道有mkfifo函数创建由open函数打开
    (3) fifo 之间的两个进程可以没有血缘关系, 而 pipe 之间的两个函数有血缘关系

3.代码演示
//ClientPipe.c
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>

int main()
{
    int wfd = open("mypipe", O_WRONLY);
    if(wfd == -1)//dakashibai
    {
        perror("open");
        exit(1);
    }

    char buf[1024];
    buf[0] = 0;
    ssize_t s;
    while(1)
    {
        printf("Please Enter#");
        fflush(stdout);
        s = read(0, buf, sizeof(buf));
        if(s > 0)//成功读取
        {
            buf[s] = 0;
            write(wfd, buf, s);
        }

        else if(s <= 0)//读取失败
        {
            perror("read");
            exit(1);
        }
    }
}
//ServerPipe.c
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/types.h>

int main()
{
    int fifo = mkfifo("mypipe", 0644);
    if(fifo == -1)//管道创建失败
    {
        perror("mkfifo");
        exit(1);
    }

    //打开管道
    int rfd = open("mypipe", O_RDONLY);
    if(rfd == -1)//打开失败
    {
        perror("open");
        exit(1);
    }

    //读管道数据
    char buf[1024];
    ssize_t s;
    while(1)
    {
        buf[0] = 0;
        printf("Please wait ... \n");
        s = read(rfd, buf, sizeof(buf) -1);

        if(s > 0)//读到数据
        {
            buf[s] = 0;
            printf("client say# %s", buf);
        }

        else if(s == 0)//读完
        {
            printf("client quit, exit now\n");
            exit(0);
        }

        else//读取失败
        {
            perror("read");
            exit(1);
        }
    }

    close(rfd);
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值