2 无名管道1

1. 管道文件是一个特殊文件,它由队列实现的。在文件IO中,创建、打开一个文件是由open函数实现,但是无名管道不能用open创建,对应的函数是pipe。

创建:pipe

读:read

写:write

关闭:close

无名管道的无名是指在它在文件系统中无文件名。


2. pipe:

函数形式:int pipe(int fd[2]);

功能:创建管道,为系统调用:unistd.h

参数:文件描述符。fd[0]是读端口,fd[1]是写端口。

返回:成功0,出错-1.

3. 实例1,创建管道:

#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
  int fd[2];
  int ret;
  ret=pipe(fd);
  if(ret <0)
  {
	printf("creat pipe failure\n");
	return -1;
  }
  printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);
  return 0;
}

执行结果:

alex@alex-virtual-machine:/extra/process/002$ gcc pipe_1.c
alex@alex-virtual-machine:/extra/process/002$ ls
a.out  pipe_1.c  pipe_2.c  pipe_3.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4

4.实例2,管道读写:

管道是以队列形式实现,管道内的东西读完就删了。如果管道内没有东西可读,则会阻塞。

#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
  int fd[2];
  int ret;
  char writebuf[]="hello linux";
  char readbuf[128]={0};
  ret=pipe(fd);
  if(ret <0)
  {
	printf("creat pipe failure\n");
	return -1;
  }
  printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);

  write(fd[1],writebuf,sizeof(writebuf));
  //start read from pipe
  
  read(fd[0],readbuf,128);
  printf("readbuf=%s\n",readbuf);

  close(fd[0]);
  close(fd[1]);
  return 0;
}

执行结果:

alex@alex-virtual-machine:/extra/process/002$ gcc pipe_2.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4
readbuf=hello linux
alex@alex-virtual-machine:/extra/process/002$

5. 实例:读阻塞

#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
  int fd[2];
  int ret;
  char writebuf[]="hello linux";
  char readbuf[128]={0};
  ret=pipe(fd);
  if(ret <0)
  {
	printf("creat pipe failure\n");
	return -1;
  }
  printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);

  write(fd[1],writebuf,sizeof(writebuf));
  //start read from pipe
  
  read(fd[0],readbuf,128);
  printf("readbuf=%s\n",readbuf);

  //second read from pipe
  
  memset(readbuf,0,128);

  read(fd[0],readbuf,128);
  printf("second read after\n");

  close(fd[0]);
  close(fd[1]);
  return 0;
}

执行结果:

alex@alex-virtual-machine:/extra/process/002$ gcc pipe_3.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4
readbuf=hello linux
^C



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值