资源描述:
《08.linux的编程:进程间通信:管道》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、8.Linux的编程:进程间通信:管道例1:管道的打开和关闭函数定义#includeintpipe(intfiledes[2]);功能:fildes为两个元素的整形数组,pipe调用产生一个管道,管道的读描述符存入fildes[0],管道的写描述符存入fildes[1]。一个进程可以向fildes[1]中写入数据,另一个进程可以从fildes[0]中读出数据。Close可以关闭管道源程序/**opipe.c-Openandcloseapipe*/#include#include#include<
2、stdlib.h>intmain(void){intfd[2];/*Arrayforfiledescriptors*/if((pipe(fd))<0){perror("pipe");exit(EXIT_FAILURE);}printf("descriptorsare%d,%d",fd[0],fd[1]);close(fd[0]);close(fd[1]);exit(EXIT_SUCCESS);}例2:读写管道用read,write调用读写管道/**piperw.c-Thecorrectwaytoopenapipeandfork*achildproc
3、ess.*/#include#include#include#include#include#include#include#defineBUFSZPIPE_BUFvoiderr_quit(char*msg);intmain(intargc,char*argv[]){intfd[2];/*Filedescriptorarrayforthepipe*/intfdin;/*Descriptorforinputfi
4、le*/charbuf[BUFSZ];intpid,len;/*Createthepipe*/if((pipe(fd))<0)err_quit("pipe");/*Forkandclosetheappropriatedescriptors*/if((pid=fork())<0)err_quit("fork");if(pid==0){/*Childisreader,closethewritedescriptor*/close(fd[1]);while((len=read(fd[0],buf,BUFSZ))>0)write(STDOUT_FILENO,bu
5、f,len);close(fd[0]);}else{/*Parentiswriter,closethereaddescriptor*/close(fd[0]);if((fdin=open(argv[1],O_RDONLY))<0){perror("open");/*Sendsomethingsincewecouldn'topentheinput*/write(fd[1],"123",4);}else{while((len=read(fdin,buf,BUFSZ))>0)write(fd[1],buf,len);close(fdin);}/*Clos
6、ethewritedescriptor*/close(fd[1]);}/*Reaptheexitstatus*/waitpid(pid,NULL,0);exit(EXIT_SUCCESS);}voiderr_quit(char*msg){perror(msg);exit(EXIT_FAILURE);}执行结果:例3:更简单的父子进程管道通信相关函数#includeFILE*popen(constchar*command,constchar*mode);功能:创建一个管道,再创建一个进程执行command,之后根据mode指定的是读还是
7、写,返回管道的文件句柄intpclose(FILE*stream);功能:关闭stream对应的管道,等待通过stream与自己通信的进程的结束。源程序/**popen.c-Usingpopen()toopenapipe*/#include#include#include#include#include#defineBUFSZPIPE_BUFvoiderr_quit(char*msg);intmain(void){FILE*fp;/*FILEstreamfo
8、rpopen*/char*cmdstring="catpopen.c";charbuf[BUF