22 行在子進程開始把讀文件描述符關了, 孫子當然讀不出來. 改了就行了:
#include<sys/types.h>#include<unistd.h>
#include<cstring>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
int?main(){
int?fd[2]; if(pipe(fd)!=0){ std::cout<<"pipe?failed"<<std::endl; exit(0); } pid_t?pid=fork(); if(pid<0){ std::cout<<"fork?failed"<<std::endl; exit(0); }else?if(pid?>?0){exit(0);
}else?if(pid?==?0){ /**?孫進程還要讀,這裏不能關掉? close(fd[0]); fd[0]=-1; */ int?n_w?=?write(fd[1],"XXXXXX",10); std::cout<<"child1?write?:"<<n_w<<"long?words"<<std::endl; pid_t?pid1=fork(); if(pid1<0){std::cout<<"fork1?failed"<<std::endl;
exit(0);
}else?if(pid1?>?0){exit(0);
}else{std::cout<<"chiled2?process"<<std::endl;
close(fd[1]);
fd[1]=-1;
char?buf[1024]={0};
int?n_r?=?read(fd[0],&buf,10);
std::cout<<buf<<":"<<n_r<<std::endl; if(n_r?==?-1){std::cout<<"errno:"<<errno<<std::endl;
}
std::cout<<strlen(buf)<<std::endl;
}}
return?0;
}
執行結果:
child1 write :10long words
chiled2 process
XXXXXX:10
6