08.linux的编程:进程间通信:管道

08.linux的编程:进程间通信:管道

ID:1347356

大小:28.00 KB

页数:4页

时间:2017-11-10

08.linux的编程:进程间通信:管道_第1页
08.linux的编程:进程间通信:管道_第2页
08.linux的编程:进程间通信:管道_第3页
08.linux的编程:进程间通信:管道_第4页
资源描述:

《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

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。