我想讀取文件並返回與子進程匹配關鍵字的行,並將這些傳遞給父項,順序無關緊要。無法獲取管道的每一行文件
我的第一個問題是:是否可以只使用1個管道或第一個過程完成將關閉管道?
我的第二個問題是,我已經爲每個孩子創建了一個管道,但父母並沒有讀取所有這些管道,只顯示了第一個文件中匹配關鍵字的所有行以及第二個文件的第一行匹配並停止。 (我試過只有2個文件,但這不是問題)
假設所有文件打開並關閉工作正常。我有一個檢查所有文件打開,pipe()和fork()。其餘的不被檢查。
我的代碼如下:
#include "commons.h"
//efmalloc is error-free malloc
int main(int argc, char *argv[]){
int numargs = argc-1;
int fds[numargs][2];
pid_t n;
for (int i = 0; i < numargs; i++)
pipe(fds[i]);
for(int i = 0; i < argc-1;i++){
n = fork();
if(n==0){
close(fds[i][0]);//closing the read end of the pipe for the children
FILE * fs = fopen(argv[i+1],"r");
//// SETTING UP THE PARAMETERS FOR READING ////
char * outputdata = (char*) efmalloc(400*sizeof(char));
*outputdata = '\0';
char * line = NULL;
size_t len = 0;
int read = getline(&line, &len, fs);
int currentline = 1;
//// END OF READINGS SETUP ////
while (read >= 0) {
if(strstr(line,"keyword") != NULL) {
strcat(outputdata,argv[i+1]);
strcat(outputdata,line);
strcat(outputdata,"\0");
//Write the data in the pipe in here
write(fds[i][1],outputdata,(strlen(outputdata)+1));
*outputdata = '\0';
}
read = getline(&line, &len, fs);
currentline++;
}
free(outputdata);
fclose(fs);
close(fds[i][1]); //now closing the write end of the pipe
exit(0);
}
}
/***** PARENT PROCESS *****/
if(n!=0) {
for (int index = 0; index < numargs; index++)
close(fds[index][1]);
char * readmsg = (char*)efmalloc(BUFFER_SIZE*sizeof(char));
for(int j = 0; j < numargs; j++){
int bytes = read(fds[j][0],readmsg,BUFFER_SIZE);
while(bytes>0){
readmsg[bytes] = 0;
printf("%s\n", readmsg);
bytes = read(fds[j][0],readmsg,BUFFER_SIZE);
}
}
for(int i = 0; i < numargs;i++)
wait(NULL);
}
return 0;
}
將代碼分解爲函數。這將使調試更容易。 – sturcotte06