欢迎登陆真网站,您的到来是我们的荣幸。 登陆 注册 忘记密码? ☆设为首页 △加入收藏
欢迎加入真幸福QQ群
电脑知识: 基础知识 网络技术 操作系统 办公软件 电脑维修 电脑安全 windows7 windows8 windows10 服务器教程 平板电脑 视频播放教程 网络应用 互联网 工具软件 浏览器教程 QQ技巧 输入法教程 影视制作 YY教程 wps教程 word教程 Excel教程 PowerPoint
云南西双版纳特产小花糯玉米真空包装


wifi共享精灵如何开启软件非软AP模式
wifi共享精灵手机无法加入网络怎么办
wifi共享精灵的网卡兼容性
linux下的进程等待
酷盘PC版如何自动备份移动设备中的照片
Centos硬件信息查看命令
linux之计划任务管理
linuxloadavg笔记整理
Hadoop是什么
酷狗如何随机选歌听
Linux下的无名管道pipe的设计
【 来源:网络 】【 点击:1 】 【 发布时间:2017_03_03 08:59:59 】

   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@wl-MS-7673:/home/wl/桌面/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 errorn");

  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 %sn",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@wl-MS-7673:/home/wl/桌面/c++# g++ pipe_test.cpp -o pipe_test

  root@wl-MS-7673:/home/wl/桌面/c++# ./pipe_test

  parent write1 Hello!

  parent write2 Pipe!

  10 numbers read from the pipe is Hello Pipe

  root@wl-MS-7673:/home/wl/桌面/c++#

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

本网站由川南居提供技术支持,fkzxf版权所有 浙ICP备12031891号
淳安分站 淳安分站