linux中pipe_rw.c的详解

来源:互联网 发布:centos smb unrec 编辑:程序博客网 时间:2024/06/03 18:43


#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>int main(){int pipe_fd[2];  /*两个管道描述符,一个读、另一个写*/pid_t pid;/*ID*/char buf_r[100];/*一个buffer用于读的数组*/.char* p_wbuf;/*一个buffer用于写的指针*/int r_num;/*读的数值。eg:返回的数据量*/memset(buf_r,0,sizeof(buf_r));/*将buf_r数组中的所有数据用0覆盖,覆盖个数为sizeof(buf_r)个*/if(pipe(pipe_fd)<0)/*pipe()<0表示创建管道失败,打印出错信息*/{printf("pipe create error\n");return -1;}if((pid=fork())==0)/*fork()创建一个子进程(子进程创建成功,会自动继承父进程的所有管道描述符、管道信息,表示访问于同一个管道)。pid=0(即fork()=0)表示在子进程中*/{printf("\n");/*回车*/close(pipe_fd[1]);/*关闭写管道描述符*/sleep(2);/*休眠2秒*/if((r_num=read(pipe_fd[0],buf_r,100))>0){/*read表示从读管道描述符中读,读取的存放位置是buf_r,读的预期个数为100,read()>0表示读取成功。读取的数目放在r_num中*/printf(   "%d numbers read from the pipe is %s\n",r_num,buf_r);/*打印读取的字符数、读取的字符串*/}close(pipe_fd[0]); /*关闭读管道描述符*/exit(0);  }else if(pid>0)/* pid>0(即fork()>0)表示在父进程中*/{close(pipe_fd[0]); /*关闭读管道描述符*/if(write(pipe_fd[1],"Hello",5)!=-1)/*read表示通过写管道,写入字符串“Hello”,写入字符串的预期长度为5。read()不等于1,表示写入成功*/printf("parent write1 success!\n");if(write(pipe_fd[1]," Pipe",5)!=-1)printf("parent write2 success!\n");close(pipe_fd[1]); /*关闭写管道描述符*/sleep(3); /*休眠3秒*/waitpid(pid,NULL,0);/*等待进程号为pid的管道进程(即子进程)退出*/exit(0);}}/*以上语言功能是实现父进程写,子进程读*/


	
				
		
原创粉丝点击