我寫了一個管道10個整數,所以我打電話寫10次,然後我想調用讀管道一次,並將寫入的整數存儲到大小爲10的數組中,然後添加所有整數從數組變成總數。問題是閱讀後我只能得到9個整數。我做錯了什麼?從管道問題讀取
int main()
{
int fd[2];
int total = 0;
int result;
int nbytes;
int child;
int subVector;
int written;
static int readSum[P];
int partialSum;
if(pipe(fd) < 0){
perror("pipe");
}
for(child = 0; child < P; child++){
if((pid[child] = fork()) < 0){
perror("fork");
exit(1);
}
else if(pid[child] == 0){
close(fd[0]);
partialSum = getSubvectorSum(elementsList,child,P,SIZE);
//printf("Partial sum: %d by child #%d\n",partialSum,getpid());
written = write(fd[1],&partialSum,sizeof partialSum);
//printf("Child #%d has written: %d bytes.\n",getpid(),written);
if(written == 0){
printf("Writting not performed.");
}
close(fd[1]);
exit(0);
}
}
close(fd[1]);
int status = 0;
nbytes = read(fd[0],&readSum,sizeof readSum);
printf("Parent reads %d bytes\n",nbytes);
if(nbytes > 0){
for(child =0;child<P;child++){
total += readSum[child];
printf("Partial sum in father: %d\n",readSum[child]);
}
}
else{
printf("Failed to read.");
}
}
如果您使用非阻塞IO,請調用讀入週期。 – Basilevs
我用週期閱讀,一切都很好,但我很好奇:爲什麼不這樣工作? – laura
什麼是'static int readSum [P] = NULL;'應該是? – glglgl