#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdint.h>
#include "../lve-ctl.h"


struct liblve *lve;


main() 
{
  const char* strId;
  int procId;
  int child[20];
  int i,j;
  pid_t pID;
  
  int rc;
  pID=0;
  rc = lve_instance_init(NULL);
  printf("LVE data size %d\n", rc);
  lve = malloc(rc);
  rc = lve_instance_init(lve);
  if (rc != 0) {
    printf("Can't init lve instance %d\n", rc);
    _exit(-1);
  }
  printf("Successfull init lve instance %d - %d\n", rc, getpid());
  

  for (i = 0; i < 20; i++) {
    pID = fork();
    if (pID == 0) { //child
      uint32_t p_cookie;
      if (lve_enter(lve, 900, -1, -1, &p_cookie)) {
	exit(-1);
      }
      strId = "Child Proc: ";
      procId = i;
      while (1) { j++; }
      if (lve_leave(lve, &p_cookie)) {
	printf("lve_leave failed");
	exit(-1);
      }
      break;
    } else if (pID < 0) { //failed to fork
      printf("Failed to fork\n");
      lve_instance_destroy(lve);
      exit(1);
    } else { //parent
      child[i] = pID;
      strId = "Parent process:";
      procId = i;
    }
  }
  int status;
  pid_t childPid;
  if (pID > 0) {
    for (i = 0; i<20; i++) {
      childPid = wait(&status);
      printf("One child is gone %d:%d:%d\n", childPid, status>>8, i);

    }
  }
  printf("%s:%d:%d\n", strId, procId,getpid());
  if (pID > 0) {
    lve_instance_destroy(lve);
  }
 return 0;
}
