Sam
Sam

Reputation: 505

Producer-Consumer Error in C

I'm trying to implement the Producer Consumer Algorithm in C so that producer.c takes in one character from a mydata.txt file and puts it into the shell variable DATA then consumer.c will read it from DATA and print it out. The output must be in the same format. All the while, producer.c and consumer.c gives the TURN to each other during the busy loop.

When I compile the program, I'm getting an error: error: too few arguments to function call, expected 1, have 0 because of both wait() functions. Please let me know if I did something wrong. I'm not sure if you'd need all the code but I hope this isn't too much!

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);

}

Upvotes: 3

Views: 246

Answers (1)

TheSHEEEP
TheSHEEEP

Reputation: 3132

The wait function requires an argument, as the error tells you.
An address to an integer, to be precise.

Upvotes: 1

Related Questions