#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <err.h>
int fibo (int n){
    
    if (n <= 0) return 0;
    else if (n <= 1) return 1;
    else return fibo(n - 1) + fibo(n - 2);
    
}
int wait_child(int x){

    if(x < 0) return -1;

    int wstatus;
    pid_t pid = fork();

    if(pid < 0) return -1;

    // Child 
    else if (pid == 0) {
        
       if (x < 0) exit(-1); 
       
       exit(fibo(x));
    }

    // Daddy
    else {

        if(waitpid(pid, &wstatus, 0) == -1) return -1;
        
        if(wstatus == -1) return -1;
        
        if (WIFEXITED(wstatus)){
            int rslt = WEXITSTATUS(wstatus);

            if (rslt == 255) rslt = -1;
            
            printf("My child knows how to count the Fibonacci sequence. He found %i for %i!\n",rslt, x);
 
        }
        
        return 0;
    }
}
/*
int main(){
    int res = wait_child(-1);
printf("%d\n",  res);                       // -1

res = wait_child(7);                        // 13
printf("%d\n", res);                        // 0
}*/
