区。pipe函数调用成功返回0,调用失败返回-1。
1父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。2. 父进程调用fork创建⼦进程,那么子进程也有两个文件描述符指向同一管道。3. 父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道⾥读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通信。
例如
#include<stdio.h>#include<unistd.h>#include<errno.h>#include<string.h>#include<sys/wait.h>int main(){ int fds[2]={ -1,-1 }; if(pipe(fds)<0) { PRintf("pipe error.%s/n",strerror(errno)); return 2; } pid_t id=fork(); if(id==0) { close(fds[0]); int count=5; char* msg="hello world/n"; while(count--) { write(fds[1],msg,strlen(msg)); printf("write success. %d/n",count); } close(fds[1]); } else{ close(fds[1]); int count=0; char buf[1024]; while(count++<10){ ssize_t s=read(fds[0],buf,sizeof(buf)-1); if(s>0) { buf[s]='/0'; } printf("father msg from child:%s",buf); if(waitpid(id,NULL,0)<0) { return 3; } } } return 0;}结果
新闻热点
疑难解答