开发者

C/Unix Programming Problem with Pipes

开发者 https://www.devze.com 2023-02-20 16:00 出处:网络
So I\'m writing a program that will take in an input file as follows: 1 1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 It will fork() a new child process for each row, and each child process will calculate the sum

So I'm writing a program that will take in an input file as follows:

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

It will fork() a new child process for each row, and each child process will calculate the sum of their respective row (it has been hardcoded in, though it would be trivial to change it to a general case).

The code is as follows:

#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开发者_Python百科=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
 }

The code ran fine once, and the only error was that the Parent average (sum) was not being calculated. However, when I ran it again, it halts after printing the first Child's sum (in this case, 4). Why could this be happening if it ran once already? What is causing it to halt?


There are multiple problems with your code:

  • the parent process reads into buf for which you haven't allocated memory (this is the most likely reason why the whole shebang is crashing);
  • you're writing childsum as binary data but trying to read it as an ASCII string containing the number.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号