简体   繁体   中英

C/Unix Programming Problem with Pipes

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=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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM