linux 匿名、命名管道的实现

一、匿名管道
匿名管道根据父子进程共享代码,父进程创建一个管道文件,并有两个文件描述符指向管道文件,子进程也有两个文件描述符指向管道文件。利用文件描述符,一端关闭读,一端关闭写,来实现通信。

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
    int _pipefd[2] = {0,0};
    if(pipe(_pipefd) < 0){
        perror("pipe");
        return 1;
    }
    pid_t id = fork();
    if(id < 0){
        perror("fork");
        return 2;
    }else if(id == 0){
        close(_pipefd[0]);
        int i = 0;
        const char *msg = "hello bit\n";
        int count = 5;
        while(count){
            msg = "i am child!";
            write(_pipefd[1],msg,strlen(msg));
            sleep(1);
            count--;
        }
        close(_pipefd[1]);
        exit(0);
    }else{ 
        close(_pipefd[1]);
        char _mesg[100];
        int j = 0;
        while(j < 100)
        {
            memset(_mesg,'\0',sizeof(_mesg));
            int ret = read(_pipefd[0],_mesg,sizeof(_mesg));
            printf("%s:code is:%d\n",_mesg,ret);
            j++;
        }
        if(waitpid(id,NULL,0)<0)
        {
            return 3;
        }
    }
    return 0;
}

二、命名管道
命名管道可以让两个没有任何关系的进程实现通信
1.创建一个管道文件,进程权限为只读

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
    umask(0);
    if(mkfifo("./fifo",0666|S_IFIFO)<0){
        perror("mkfifo");
        return 1;
    }

    int fd = open("./fifo",O_RDONLY);
    if(fd < 0){
        perror("open");
        return 2;
    }
    char buf[128];
    while(1){
        ssize_t s = read(fd,buf,sizeof(buf));
        if(s > 0){
            buf[s] = "\0";
            printf("client#%s\n",buf);
        }else if( s==0){
            printf("client quit! I quit!\n");
            break;
        }else{
            perror("read");
        }
    }

    close(fd);
    return 0;
}
2.让另一个进程也操作这个管道文件,权限为只写
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{

    int fd = open("./fifo",O_WRONLY);
    if(fd < 0){
        perror("open");
        return 2;
    }
    char buf[128];
    while(1){
        printf("please Enter#");
        fflush(stdout);
        ssize_t s = read(0,buf,sizeof(buf));
        if(s > 0){
            buf[s-1] = "\0";
            write(fd,buf,strlen(buf));  

        }
    }

    close(fd);
    return 0;
}

三、实现

1.必须先执行创建管道的进程server
这里写图片描述
2.再执行client写入
这里写图片描述
3.server看到client写入的内容
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值