#include <stdlib.h>
#include <stdio.h>
#include <sys/file.h>

#define REQUESTPIPE "reqpipe"
#define RESPONSEPIPE "respipe"

int main (int argc, char** argv) {

  int ret;
  FILE* reqpipe;
  FILE* respipe;
  char buffer[128];

  /* Anfrage- und Antwort-Pipe oeffnen */
  puts("opening pipes");
  reqpipe = fopen(REQUESTPIPE, "r+");
  if (reqpipe == NULL) {
    perror("can't open request pipe");
    close(reqpipe);
    flock(REQUESTPIPE, LOCK_UN);
    exit(1);
  }
  respipe = fopen(RESPONSEPIPE, "r+");
  if (respipe == NULL) {
    perror("can't open response pipe");
    close(respipe);
    flock(RESPONSEPIPE, LOCK_UN);
    exit(1);
  }

  while (1) {

    /* Die Pipe fuer den Zugriff sperren */
    puts("locking request pipe");
    ret = flock(reqpipe->_file, LOCK_EX);
    if (ret == -1) {
      perror("error locking request pipe");
      exit(1);
    }
    /*puts("locking response pipe");
    ret = flock(respipe->_file, LOCK_EX);
    if (ret == -1) {
      perror("error locking response pipe");
      exit(1);
    }*/

    /* Die Anfrage an den Server stellen */
    puts("sending request");
    fprintf(reqpipe, "Send me a cookie\n");
    fflush(reqpipe);
    sleep(1);

    /* die Antwort aus der Pipe lesen und ausgeben */
    puts("reading response");
    fgets(buffer, sizeof(buffer), respipe);
    if (ferror(respipe)) {
      perror("error reading pipe");
      close(respipe);
      exit(1);
    } else if (feof(respipe)) {
      puts("server exited");
      close(respipe);
      exit(0);
    }
    printf(buffer);

    puts("unlocking pipes");
    ret = flock(reqpipe->_file, LOCK_UN);
    if (ret == -1) {
      perror("locking request pipe error");
      close(reqpipe);
      exit(1);
    }
    /*ret = flock(respipe->_file, LOCK_UN);
    if (ret == -1) {
      perror("locking response pipe error");
      close(respipe);
      exit(1);
    }*/

    puts("sleeping");
    sleep(5);

  }
}
