嗨,我有一個 C 程式,它基本上假設在 linux 中模擬管道函式并寫入在 .txt 檔案中讀取的位元組數,因此
./a.out cat test : grep -v le : wc -l
我想弄清楚的問題是
為什么在檔案中寫入相同數量的位元組,因為我知道每個行程回傳不同的數量?
這段代碼在父行程中執行,并嘗試使用讀取系統呼叫計算每個輸出的位元組數,并將輸出寫入下一個行程的寫入系統呼叫中,以便下一個行程可以使用輸出作為他的輸入。
所以假設我有這些管道a | b | c
這段代碼將讀取輸出a并將其寫入,b以便b可以將其用作輸入等等。
for (int i = 1; i < processes-1; i ) {
close(apipe[i][1]);
char str[4096];
int count=0;
int nbChar=0;
while(1){
count=read(apipe[i][0],str,sizeof(str));
nbChar =count;
if(count==-1){
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
}else if(count==0)break;
}
char *leInput=(char*)malloc(nbChar*sizeof(char));
strncpy(leInput,str,nbChar);
if(i>0){
fprintf(fp, "%d : %d \n ", i,nbChar);
}
close(apipe[i][0]);
write(apipe[i 1][1], leInput, nbChar);
}
uj5u.com熱心網友回復:
每次通過while(1)回圈時,您都會讀入 的開頭str,而不是您在上一次迭代中中斷的地方。因此,您正在用下一次讀取覆寫上一次讀取。
您應該leInput通過回圈每次遞增復制。然后您可以使用realloc()它來增長它以容納新的輸入,并且您可以leInput nbChar在您完成上一次的地方之后使用它進行復制。
for (int i = 1; i < processes-1; i ) {
close(apipe[i][1]);
int nbChar=0;
char *leInput = NULL;
while(1){
int count=0;
char str[4096];
count=read(apipe[i][0],str,sizeof(str));
if(count==-1){
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
} else if(count==0) {
break;
}
leInput = realloc((nbChar count)*sizeof(char));
memcpy(leInput nbChar, str, count);
nbChar = count;
}
if(i>0){
fprintf(fp, "%d : %d \n ", i,nbChar);
}
close(apipe[i][0]);
write(apipe[i 1][1], leInput, nbChar);
}
或者,您可以只寫入內部回圈中的下一個管道,而無需將所有內容都收集到leInput:
for (int i = 1; i < processes-1; i ) {
int nbChar = 0;
close(apipe[i][1]);
while(1){
int count=0;
char str[4096];
count=read(apipe[i][0],str,sizeof(str));
if(count==-1){
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
} else if(count==0) {
break;
}
write(apipe[i 1][1], str, count);
nbChar = count;
}
if(i>0){
fprintf(fp, "%d : %d \n ", i,nbChar);
}
close(apipe[i][0]);
close(apipe[i 1][1])
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/379247.html
