linux中无名管道,Linux下的无名管道pipe的设计

1. 函数说明

pipe(建立管道):

1) 头文件 #include

2) 定义函数: int pipe(int filedes[2]);

3) 函数说明: pipe()会建立管道,并将文件描述词由参数filedes数组返回。

filedes[0]为管道里的读取端

filedes[1]则为管道的写入端。

4) 返回值:  若成功则返回零,否则返回-1,错误原因存于errno中。

错误代码:

EMFILE 进程已用完文件描述词最大量

ENFILE 系统已无文件描述词可用。

EFAULT 参数 filedes 数组地址不合法。

示例:

root@www.linuxidc.com:/home/linuxidc/桌面/c++# cat -n pipe_test.cpp

1

2 #include

3 #include

4 #include

5 #include

6 #include

7 #include

8 #include

9 /*

10  * 程序入口

11  * */

12 int main()

13 {

14  int pipe_fd[2];

15  pid_t pid;

16  char buf_r[100];

17  char* p_wbuf;

18  int r_num;

19

20  memset(buf_r,0,sizeof(buf_r));

21

22  /*创建管道*/

23  if(pipe(pipe_fd)<0)

24  {

25   printf("pipe create error\n");

26   return -1;

27  }

28

29  /*创建子进程*/

30  if((pid=fork())==0)  //子进程执行序列

31  {

32   printf("\n");

33   close(pipe_fd[1]);//子进程先关闭了管道的写端

34   sleep(2); /*让父进程先运行,这样父进程先写子进程才有内容读*/

35   if((r_num=read(pipe_fd[0],buf_r,100))>0)

36   {

37    printf("%d numbers read from the pipe is %s\n",r_num,buf_r);

38   }

39   close(pipe_fd[0]);

40   exit(0);

41   }

42  else if(pid>0) //父进程执行序列

43  {

44   close(pipe_fd[0]); //父进程先关闭了管道的读端

45   if(write(pipe_fd[1],"Hello",5)!=-1)

46    printf("parent write1 Hello!\n");

47   if(write(pipe_fd[1]," Pipe",5)!=-1)

48    printf("parent write2 Pipe!\n");

49   close(pipe_fd[1]);

50   wait(NULL); /*等待子进程结束*/

51   exit(0);

52  }

53  return 0;

54 }

55

56

root@www.linuxidc.com:/home/linuxidc/桌面/c++# g++ pipe_test.cpp -o pipe_test

root@www.linuxidc.com:/home/linuxidc/桌面/c++# ./pipe_test

parent write1 Hello!

parent write2 Pipe!

10 numbers read from the pipe is Hello Pipe

root@www.linuxidc.com:/home/linuxidc/桌面/c++#

无名管道的创建是在fork创建前,通过pipe()创建管道,然后通过fork创建子进程,之后,子进程会拷贝父进程的代码段/数据段及堆栈段,因此,创建的管道会被复制一份,子进程一份,父进程一份,为了使管道正常通讯,必须处理已有管道。0b1331709591d260c1c78e86d0c51c18.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值