[英]C/Unix Programming Problem with Pipes
因此,我正在编写一个程序,该程序将采用以下输入文件:
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)后暂停。 如果已经运行过一次,为什么会发生这种情况? 是什么导致它停止?
您的代码有多个问题:
buf
(这是整个shebang崩溃的最可能原因); childsum
写为二进制数据,但尝试将其作为包含数字的ASCII字符串读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.