C中的生产者 - 消费者错误

时间:2017-12-04 03:47:01

标签: c

我试图在C中实现Producer Consumer Algorithm,以便producer.cmydata.txt文件中接收一个字符并将其放入shell变量DATA然后consumer.c将从DATA读取并打印出来。输出必须采用相同的格式。在忙碌循环期间,producer.cconsumer.c始终给予彼此TURN。

编译程序时,由于error: too few arguments to function call, expected 1, have 0两个函数,我收到错误:wait()。如果我做错了,请告诉我。我不确定您是否需要所有代码,但我希望这不是太多!

main.c中:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "producer.c"
#include "consumer.c"

int main(){
  char turn;
  FILE *mydata = fopen("mydata.txt", "rt");

  // Writing 0 into TURN.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);

  putc('0', TURN);
  fclose(TURN);

  int pid = fork();

  // Program done when turn == 'x'
  while(turn - 'x' != 0){

    TURN = fopen("TURN.txt", "rt");
    turn = getc(TURN);
    fclose(TURN);

    // producer() uses pointer to mydata.txt, to avoid having to reopen in producer.c each time
    if(pid == -1){ exit(1); }
    if(pid == 0){ producer(mydata); wait(); }
    if(pid != -1){ consumer(); wait(); }

  }

  fclose(mydata);

  return 0;
}

Producer.c:

#include <stdio.h>
#include <stdlib.h>

void producer(FILE *mydata){
  FILE *DATA;

  // Writing 1 character from mydata.txt to DATA.txt
  DATA = fopen("DATA.txt", "wt");
  if(DATA == NULL) exit(1);
  fprintf(DATA, "%c", getc(mydata));
  fclose(DATA);

  // Writing '1' into TURN.txt for consumer, or 'x' if done reading mydata.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);
  if(!feof(mydata))
    putc('1', TURN);
  else
    putc('x', TURN);
  fclose(TURN);
}

consumer.c:

#include <stdio.h>
#include <stdlib.h>

void consumer(){

    FILE *DATA;

    DATA = fopen("DATA.txt", "r");
    if(DATA == NULL) exit(1);
    int c;
    if(DATA == NULL) { exit(1); } 
    do {
    c = fgetc(DATA);
      if( feof(DATA) ) {
         break ;
      }
      printf("%c", c);
    } while(1);

    fclose(DATA);

    FILE *TURN = fopen("TURN.txt", "wt");
    if(TURN == NULL) exit(1);
    if(!feof(DATA))
      putc('0', TURN);
    else
      putc('x', TURN);
    fclose(TURN);

}

1 个答案:

答案 0 :(得分:1)

wait function需要一个参数,因为错误告诉你 确切地说,是一个整数的地址。