#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>

void pipe_handler(int sig) 
{
    write(STDERR_FILENO, "pipe handler called: SIGPIPE received (13)", 42); // write is safe.
    exit(sig);
}

int is_valid_fd(int fd)
{
    return fcntl(fd, F_GETFL) != -1 || errno != EBADF;
}

int main()
{
  signal(SIGPIPE, pipe_handler);
  
  int pfd[2];
  char buf;
  
  pipe(pfd);
  printf("read fd valid: %i\n", is_valid_fd(pfd[0]));
  printf("write fd valid: %i\n", is_valid_fd(pfd[1]));

  close(pfd[0]); // this will send SIGPIPE -> handler if I later try to write. It will also prevent reads
  write(pfd[1], "Hello!", 6);
  close(pfd[1]); // done writing; no more writes allowed
  write(pfd[1], "I'm invisible!", 14); // this won't sent SIGPIPE, but will set errno = 9, EBADF
  
  while (read(pfd[0], &buf, 1) > 0) {
      write(STDOUT_FILENO, &buf, 1); // read in data 1 char at a time)
  }
    
  write(STDOUT_FILENO, "\n", 1);
  
  close(pfd[0]); // now pipe is closed on both ends: no leaks!
  
  printf("read fd valid: %i\n", is_valid_fd(pfd[0]));
  printf("write fd valid: %i\n", is_valid_fd(pfd[1]));
  
  // try to close fd twice
  //int c = close(pfd[0]); // will set errno = 9, EBADF
  //printf("close: %i, %i\n", c, errno);
  
  // try to write after closing off both ends of pipe
  // int w = write(pfd[1], "Hello!", 6); // this will set errno = 9, EBADF 
  // since pfds are closed and no longer valid
  // printf("write: %i, %i\n", w, errno);
  
  return 0;
}