无名管道

管道:

  1. 它是半双工的(数据只能在一个方向上流动)具有固定的读端和写端。
  2. 它只能用于父子进程或兄弟进程之间的通信。
  3. 它可以看成一种特殊的文件,它的读写可以使用read和write等函数;但它不是普通文件,不属于其他任何文件系统,只存在于内存中。
  4. 管道数据读走就没了。

 建立管道:(无名管道)

  • int pipe(int fd[2]);
  1. 返回值:成功返回0,失败返回-1。
  • 当一个管道建立时,它会创建两个文件描述符,f[0]为读而打开,f[1]为写而打开。
  1. fd[0]对应读: read(fd[0],__,__);
  2. fd[1]对应写: write(fd[1],__,__);
  • 关闭管道:只需将两个文件描述符关闭即可。
  1. close(fd[0]);     close(fd[1]);
  • 管道读写时:
  1. 读时先关闭写:close(fd[1]);
  2. 写时先关闭读:close(fd[0]);

 #include <unistd.h>

int pipe(int pipefd[2]);

代码如下:

#include <unistd.h>
#include <string.h>
#include <stdio.h> 

int main()
{
        int fd[2];
        int pid;
        char buf[128];

        if(pipe(fd) == -1){
                printf("pipe is fail\n");
        }

        pid = fork();

        if(pid < 0){
                printf("creat fork is fail\n");
        }

        if(pid >0){
                sleep(3);
                printf("this is father \n");

                close(fd[0]);
                write(fd[1],"hello this is father",strlen("hello this is father"));
        }

 if(pid == 0){
                printf("this is child \n");

                close(fd[1]);
                read(fd[0],buf,128);
                printf("read from father:%s\n",buf);
        }


        return 0;
}

运行结果: 

this is father 
this is child 
read from father:hello this is father 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值