Linux 管道文件

管道分为无名管道和有名管道两种管道,管道文件是建立在内存之上可以同时被两个进程访问的文件。

先来说说有名管道:
mkfifo函数创建有名管道,属于系统调用。

在linux操作系统中为实现下述功能,
在这里插入图片描述

先创建一个有名管道文件fifo。

再写出两个对管道文件进行操作的程序,一个只读,另外一个只写。

只读:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

int main()
{
int fdr=open("./fifo",O_RDONLY);
assert(fdr != -1);

printf("fdr=%d\n",fdr);

while(1)

{
char buff[128]={0};
int n=read(fdr,buff,127);
if(n==0)
{
break;
}
printf(“buff=%s,n=%d\n”,buff,n);
}
close(fdr);
exit(0);
}

只写:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

int main()
{
int fdw=open("./fifo",O_WRONLY);
assert(fdw != -1);
printf("fdw=%d\n",fdw);
while(1)
{
    printf("intput:\n");
    char buff[128]={0};
    fgets(buff,128,stdin);

    if(strncmp(buff,"end",3)==0)
    {
      break;
    }
    write(fdw,buff,strlen(buff)-1);
}
close(fdw);

exit(0);
}

在这里插入图片描述

分别在不同的bush里面,在运行只写的里面写入字符,只读那边就会将写好的字符打印出来。

总结:1.管道为空,读read阻塞
2.管道为满,写write阻塞

关闭管道写端,读就返回为0,不再阻塞
关闭管道的读端,写端,写入数据时,会产生异常

**

##无名管道

**

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>//使用无名管道要引用的头文件

//父子进程,父进程写入,子进程读取
int main()
{
int fd[2];//两个文件描述符
int res=pipe(fd);
assert(res != -1);

pid_t pid=fork();
assert(pid !=-1);

if(pid==0)
 {
     close(fd[1]);//关闭写端
     char buff[128]={0};
     read(fd[0],buff,127);
     printf("buff=%s\n",buff);
     close(fd[0]);//关闭读端
 }
 else
 {
     close(fd[0]);//关闭读端
     write(fd[1],"hello",5);
     close(fd[1]);//关闭写端
 }

 exit(0);

}

有名管道和无名管道的区别?
有名管道可以在任意两个进程之间通讯,而无名管道只能在父子进程之间通迅。

写入管道的数据是在内存中还是磁盘中?
在内存中,无论有名无名。

管道的通讯是全双工还是半双工?
半双工。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值