我的程序旨在从文件读取数据,但我只是希望它使用管道将整数返回给父级。但是,当我运行它时,进程永远无法达到从子级读取或写入数据的目的。任何提示或解决方案将不胜感激。最具体地讲,如何使用持有每个孩子ID的pid数组将孩子的数据返回给父母?
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char** argv){
int sum, i, numOfChildren, fileSize;
struct stat st;
char *filename, c;
FILE *fp;
//check num of arguments
if(argc != 3){
perror("Usage: pSum filename numberOfChildren");
return 1;
}
filename = argv[1];
numOfChildren = atoi(argv[2]);
// open file to read size
if(stat(filename, &st)== 0){
fileSize = st.st_size;
}
else{
perror("File could not be opened");
return 1;
}
// calculate file size and partitions
int partition = fileSize/numOfChildren;
int fd[numOfChildren][2];
pid_t childProc[numOfChildren];
for(i = 0; i < numOfChildren; i++){
int childCount;
//calculate offset and how far to read
//open pipe and fork
pipe(fd[i]);
childProc[i] = fork();
// child work
if(childProc[i] == 0){
// close write side of pipe
close(fd[i][1]);
// open file and set position
fp = fopen(filename, "r");
if(fp == NULL){
perror("file unable to be opened");
return 1;
}
// read data from file, sum, and pipe to parent
/* while((c=fgetc(fp)) != EOF){
printf("%c", c);
} */
childCount = 5;
write(fd[i][1], &childCount,sizeof(childCount));
// close pipe and file
// close reading end of pipe
close(fd[i][0]);
fclose(fp);
// return sum
return childCount;
}
}
//close read pipe and modify file variables
// get values from children and sum them
sum = 0;
int status;
pid_t pid;
printf("number of partitions %d\n", partition);
sleep(5);
for(i = 0; i < numOfChildren; i++){
waitpid(childProc[i],&status,0);
printf("child %d is being read", i);
read(fd[i][0], &status, sizeof(int));
close(fd[i][0]);
sum = sum + status;
}
// print results
printf("The total sum of the file is %d\n", sum);
return 0;
}