C fork和pipe从文件中添加数字

时间:2016-10-23 20:26:10

标签: c pipe fork

执行时,同一文件的总计不同。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_FILE_NAME 100
#define RUNS 1

int main() {    
    int num,i;
    FILE *fp;
    char*s, buf[1024];
    int count =0;
    char c;
    char filename[MAX_FILE_NAME];
    printf("Enter filename: ");
    scanf ("%s",filename);
    if ((fp =fopen(filename, "r"))  == NULL)    {
        printf("Error");
        exit(1);
    }
    fscanf(fp,"%d",&num);
    for (c = getc(fp); c!= EOF; c = getc(fp))
    {
        if (c == '\n'){
            count = count+1;
        }
    }
    printf("%s has %d numbers \n", filename, count);
    int f;
    printf("Choose from the options how many processes you want to use [1,2,4]: ");
    scanf("%i", &f);
    printf("%i processes \n", f);
    int fds[f+1][2];
    int numb[count];
    int x,k;
    time_t start, finish;
    start = time(NULL);

    for(i = 0; i < RUNS; i++)
    {
        pipe(fds[f]);
        for( x = 0; x<f; x++)
        {
            pipe(fds[x]);
            int ind[2];
            ind[0] = ((x)*(count/f));
            ind[1] = ((x+1)*(count/f));
            write(fds[x][1], &ind, 2* sizeof(int));
            if (fork() ==0)
            {
                int t =0;
                int ind2[2];
                read(fds[x][0], &ind2, 2*sizeof(int));
                for( k = ind2[0]; k<ind2[1]; k++)
                {
                    t += numb[k];
                }
                write(fds[f][1], &t, sizeof(int));
                exit(0);
            }
        }
        int m, tmp, total;
        total = 0;
        for( m = 0; m < f; m++)
        {

        for( m = 0; m < f; m++)
        {
            read(fds[f][0], &tmp, sizeof(int));
            sleep(5);
            total += tmp;
        }
        printf("DOne calc \n");
        printf("Total: %i \n", total);
    }
    finish = time(NULL);
    float runtime = (float)((finish-start)/RUNS);
    printf("runtime: %f \n", runtime);
    fclose(fp);
    return 0; 
}

1 个答案:

答案 0 :(得分:1)

您获得相同输入的随机结果,因为计算基于未初始化的int numb[count];值。

根据C99标准,第6.7.8.10节:

  

如果没有显式初始化具有自动存储持续时间的对象,则其值是不确定的。

因为它int numb[count];包含一些来自内存的随机垃圾。要获得预测结果,请使用显式初始化:

#include <string.h>  // memset

int numb[count]; 
memset (numb, 0, sizeof(numb));  // Zero-fills

使用下面的代码将filename文件中的数字放入numb

int i = 0;
char line[1024];
fseek(fp, 0, SEEK_SET);
while(fgets(line, sizeof(line), fp) ) 
{
  if( sscanf(line, "%d", &numb[i]) == 1 )  // One number per line 
  {
    ++i;
  }
}