#include "headers.h"

pid_t find_child(){
  char procdir[256] = "/proc";
  char readbuf[256];
  int proc_fd;
  pid_t par_pid;
  int read_size;
  int pid_fd;
  pid_t child_int_pid;
  int foobar;
  const char *file_str = "cmdline";
  const char *pid_file = "/tmp/alarm.pid";
  char child_pid[MY_MAX];
  /* Check to see if the child is alive */
  if((pid_fd = open(pid_file, O_RDONLY)) < 0){
    /* No child is here */
    return 0;
  }
  if((foobar = read(pid_fd, child_pid, 256)) < 0){
    fprintf(stderr, "%s: read() in find_child\n", strerror(errno));
    abort();
  }
  strcat(procdir, "/");
  strcat(procdir, child_pid);
  strcat(procdir, "/");
  strcat(procdir, file_str);
  if((proc_fd = open(procdir, O_RDONLY)) < 0){
    /* Child isn't here */
    return 0;
  }
  /* Now read it and look for our program */
  read_size = read(proc_fd, readbuf, 256);
  if(read_size > 0){
    if(close(proc_fd) < 0){
      fprintf(stderr, "%s: close() in /proc in find_child\n", strerror(errno));
      abort();
    }
    child_int_pid = atoi(child_pid);
    return child_int_pid;
  }
  if(close(proc_fd) < 0){
    fprintf(stderr, "%s: close() in /proc in find_child\n", strerror(errno));
    abort();
  }
  return 0;
}