#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <ctype.h>
#include <errno.h>

#define K	1024

void parent(pid_t pid, int s[2])
{
  char buf[K];
  int r, c, w;
  
  close(s[1]);
  while((r = read(STDIN_FILENO, buf, K)) > 0) {
    // Send the message:
    w = write(s[0], buf, r);
    // Read the response:
    c = read(s[0], buf, K);
    // Write it to the screen:
    write(STDOUT_FILENO, buf, c);
  }
  close(s[0]);
  waitpid(pid, NULL, 0);
  return;
}

void child(int s[2])
{
  char *uconv = "NOPQRSTUVWXYZABCDEFGHIJKLM";
  char *lconv = "nopqrstuvwxyzabcdefghijklm";
  char buf[K];
  int r, w;

  close(s[0]);

  while((r = read(s[1], buf, K)) > 0) {
    for(int i=0; i < r; i++) {
      if (isalpha(buf[i])) {
	if (islower(buf[i])) buf[i] = lconv[buf[i] - 'a'];
	else buf[i] = uconv[buf[i]-'A'];
      }
    }
    write(s[1], buf, r);
  }
  close(s[1]);

  exit(0);
}

int main(void)
{
  int sv[2];
  
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
    perror("socketpair");
    return 1;
  }

  pid_t pid = fork();
  if (pid < 0) {
    perror("fork");
    return 1;
  }
  if (pid == 0) child(sv);
  else parent(pid, sv);
}
