2011-03-30 4 views
0

에 문제가 :C/유닉스 프로그래밍 그래서 다음과 같이 입력 파일에 걸릴 프로그램을 쓰고 있어요 파이프

1 1 1 1 
1 1 1 1 
1 1 1 1 
4 4 4 4 

그것은 포크 것() 새로운 자식 프로세스를 각 행에 대해, 그리고 각 아동 프로세스는 각각의 행의 합계를 계산합니다 (일반적인 경우로 변경하는 것은 사소한 일이지만 하드 코드 된 것입니다). 다음

코드는 :

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <string.h> 
#include <sys/wait.h> 
#include <ctype.h> 

#define cols 100 //not used 
#define rows 4 //easily modifiable 

int main() 
{ 
int count=0; //count for children 
int fd[2]; 
FILE *fp = fopen("input.dat", "r"); 
setbuf(fp,NULL); //unbuffered 

double sum = 0; //parent sum (and average) 
int childStatus; //used in the wait command 

char c; //char for reading in numbers 
int pid; //store process id 
int childsum=0; 

for(count=0;count<rows;count++) 
{ 
    pipe(fd); 
    pid=fork(); //duplicate process 

    if(pid==0) //if child is done 
    { 
     close(fd[0]); //close the reader 
     childsum=0; //child's sum 
     while(c!='\n') 
     { 
      fread(&c, sizeof(c), 1, fp); //read in integer 
      if(c != ' ') 
      { 
       childsum=childsum+atoi(&c); //to calculate the sum 
      } 
     } 
     write(fd[1], &childsum, sizeof(int));//write to pipe 
     printf("Child %d: %d\n", count+1, childsum); //output child's sum to the screen 
     close(fd[1]); //close remaining file 
     exit(0); //exit current child 

    } 
    else 
    { 
     close(fd[1]); //close the writer 
     //read from pipe 
     char* buf; 
     while(read(fd[0], buf, sizeof(buf))!=sizeof(buf)) 
     { 
      sum = sum + atoi(buf); 
     } 
     close(fd[0]); //close remaining file 
    } 

} 
sum = sum/count; 
printf("Parent Average: %f", sum); 
fclose(fp); 
return 0; //end 
} 

코드 미세 한번 실행 한 유일한 에러는 상위 평균 (sum)는 산출되지 이였다. 그러나 다시 실행하면 첫 번째 하위 합계 (이 경우 4)가 인쇄 된 후 중단됩니다. 한 번 실행되면 왜 이렇게 될 수 있습니까? 무엇이 멈추게할까요?

답변

3

코드에 여러 가지 문제가 있습니다 :

부모 프로세스가 buf에있는 (이 전체 오두막이 충돌하는 이유를 가장 가능성있는 이유입니다) 메모리를 할당하지 않은 읽어
  • ;
  • 당신은 바이너리 데이터로 childsum를 작성하지만, 수를 포함하는 ASCII 문자열로 읽으려고하고 있습니다.
+0

은 내가 데이터를 제대로 읽어 얻을 수있는 방법에 대한 혼란 스러워요. read() 함수를 사용하여 출력하려고합니다. – muttley91

+0

'write()'를 미러링하는'int'에'read()'하는 것은 어떻습니까? – NPE

관련 문제