區(qū)。pipe函數(shù)調(diào)用成功返回0,調(diào)用失敗返回-1。
1父進(jìn)程調(diào)用pipe開辟管道,得到兩個(gè)文件描述符指向管道的兩端。2. 父進(jìn)程調(diào)用fork創(chuàng)建?進(jìn)程,那么子進(jìn)程也有兩個(gè)文件描述符指向同一管道。3. 父進(jìn)程關(guān)閉管道讀端,子進(jìn)程關(guān)閉管道寫端。父進(jìn)程可以往管道里寫,子進(jìn)程可以從管道?讀,管道是用環(huán)形隊(duì)列實(shí)現(xiàn)的,數(shù)據(jù)從寫端流入從讀端流出,這樣就實(shí)現(xiàn)了進(jìn)程間通信。
例如
#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;}結(jié)果
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注