Проблема программирования C / Unix с трубами - PullRequest
0 голосов
/ 30 марта 2011

Итак, я пишу программу, которая будет принимать входной файл следующим образом:

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

Это будет fork () новый дочерний процесс для каждой строки, и каждый дочерний процесс будет вычислять суммусоответствующей строки (это было жестко закодировано, хотя было бы тривиально изменить его на общий случай).

Код выглядит следующим образом:

#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).Почему это может произойти, если оно уже запущено?Что вызывает его остановку?

1 Ответ

3 голосов
/ 30 марта 2011

Есть несколько проблем с вашим кодом:

  • родительский процесс считывает в buf, для которого вы не выделили память (это наиболее вероятная причина сбоя всего shebang);
  • вы пишете childsum как двоичные данные, но пытаетесь прочитать их как строку ASCII, содержащую число.
...