#include <unistd.h>
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h> 
using namespace std;

int sigstate = -1;
void signalHandler(int signalNum) {
  if (signalNum == SIGUSR1) {
  	sigstate = 1;
    printf("Caught SIGUSR1 signal.\n");
  }
}

void signalHandler2(int signalNum) {
  if (signalNum == SIGUSR2) {
  	sigstate = 0;
    printf("Caught SIGUSR1 signal.\n");
  }
}

void doprocess() {
	pid_t childPid;
	const char *dyninstapp = "./codeCoverage";

	childPid = fork();

	if( childPid >= 0 ) {
		if( childPid == 0 ) {
			char strval[10];
			memset(strval,0,10);
			sprintf(strval,"%d",sigstate);
			int erro = 0;
			erro = execlp(dyninstapp, dyninstapp, strval, NULL);
			fprintf(stderr,"Failed to launch a new streamer: %s error %d\n",dyninstapp, erro);
			exit(-1);

		}
	}
	else {
		fprintf(stderr, "fork failed for %s\n", dyninstapp);
	}

	int status; 
      
    waitpid(childPid, &status, 0); 
  
    if ( WIFEXITED(status) ) 
    { 
        int exit_status = WEXITSTATUS(status);         
        printf("Exit status of the child was %d\n",  
                                     exit_status); 
    } 
}
int main(int argc, char *argv[]) {
	signal(SIGUSR1, signalHandler);
	signal(SIGUSR2, signalHandler2);

	if(argc < 2) {
        cerr << "./codeCoverage inputbinary" << endl;
        return EXIT_FAILURE;
    }
    sigstate = atoi(argv[1]);

    while(1) {
    	if(sigstate == -1)
    		sleep(1);
    	else {
    		doprocess();
    		sigstate = -1;
    	}
    }
	
    return 0;
}