區。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;}結果
新聞熱點
疑難解答