系统之家 - Windows操作系统&装机软件下载网站!

当前位置: 首页  >  教程资讯  >  电脑教程 Linux下的无名管道pipe的设计

Linux下的无名管道pipe的设计

时间:2023-06-02 16:16:41 来源: 人气:

   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创建子进程,之后,子进程会拷贝父进程的代码段/数据段及堆栈段,因此,创建的管道会被复制一份,子进程一份,父进程一份,为了使管道正常通讯,必须处理已有管道。,

作者

教程资讯

电脑教程排行

系统教程

系统主题