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)가 인쇄 된 후 중단됩니다. 한 번 실행되면 왜 이렇게 될 수 있습니까? 무엇이 멈추게할까요?
은 내가 데이터를 제대로 읽어 얻을 수있는 방법에 대한 혼란 스러워요. read() 함수를 사용하여 출력하려고합니다. – muttley91
'write()'를 미러링하는'int'에'read()'하는 것은 어떻습니까? – NPE