簡體   English   中英

管道的C / Unix編程問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM