#include <zorp/readline.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

int main()
{
  ZStream *input;
  ZReadLine *rl;
  int pair[2];
  pid_t pid;
  gchar *line;
  gint length;
  
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) < 0)
    {
      perror("socketpair()");
      return 254;
    }
  
  pid = fork();
  if (pid < 0)
    {
      perror("fork()");
      return 254;
    }
  else if (pid != 0) 
    {
      close(pair[1]);
      write(pair[0], "1\n2\n3\n", 6);
      write(pair[0], "0123", 4);
      write(pair[0], "4567\n", 5);
      write(pair[0], "0123456789", 10);
      write(pair[0], "abc\nabc\nabcdef\n", 15);
      write(pair[0], "0123456789", 10);
      write(pair[0], "0123456789", 10);
      write(pair[0], "012345678\nabcdef\n", 17);
      close(pair[0]);
      waitpid(pid, NULL, 0);
    }
  else
    {
      int rc;
/*
      printf("%d\n", getpid());
      sleep(10);  */
      close(pair[0]);  
      input = z_stream_new(pair[1], "sockpair input");
      rl = z_read_line_new(input, 10, ZRL_EOL_NL | ZRL_TRUNCATE);
      
      rc = z_read_line_get(rl, &line, &length);
      while (ST_ERROR(rc) == ST_OK)
        {
          printf("%.*s\n", length, line);
          rc = z_read_line_get(rl, &line, &length);
        }
      close(pair[1]);
    }
  return 0;
}
