2017-02-21 27 views
0

我想讀取文件並返回與子進程匹配關鍵字的行,並將這些傳遞給父項,順序無關緊要。無法獲取管道的每一行文件

我的第一個問題是:是否可以只使用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; 
} 
+1

將代碼分解爲函數。這將使調試更容易。 – sturcotte06

回答

0

我看到幾個小問題,以及兩個巨大的:

  • getline()read()都返回ssize_t,不int。他們是不是一樣。
  • strcat(outputdata,"\0");什麼都不做。如果outputdata已正確終止,則不需要,如果outputdata尚未正確終止,則它是未定義的行爲。
  • 你不是在readmsg提供了'\0'終止足夠的空間 - 你可以讀取多達BUFFER_SIZE字節,但readmsg[BUFFER_SIZE] = 0;是分配的緩衝區之外。這是未定義的行爲。
  • 您無法確定所有數據實際上是否適合outputdata。無論實際適合多少,你都會越來越多地餡。如果你超出outputdata,你又陷入了未定義的行爲。
+0

我被給出該文件的行最多256個字符,文件的名稱是最多64個字符,我分配400,所以它是綽綽有餘。並且,我會改正它們。 – user7601055