/* select2.c (emx+gcc) */

/* Test writefds of select() with socket handles.  Up to revision
   index 33 (0.9a fix03) of emx.dll, wrong bits were set in *WRITEFDS
   and *EXCEPTFDS. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "easysock.h"

static int max_fd;

static void fd_show (fd_set *p)
{
  int i;

  for (i = 0; i <= max_fd; ++i)
    printf ("%d", FD_ISSET (i, p) ? 1 : 0);
}


int main (int argc, char *argv[])
{
  fd_set rfds, wfds, in_rfds, in_wfds;
  struct sockaddr_in in_server;
  int s1, s2, port, i, test;

  test = 0; i = 1;
  if (i < argc && strcmp (argv[i], "-t") == 0)
    test = 1, ++i;

  if (argc - i != 2)
    {
      fputs ("Usage: select2 [-t] <host> <port>\n", stderr);
      return 1;
    }

  es_parse_host (&in_server, argv[i+0]);
  es_parse_port (&port, argv[i+1]);

  in_server.sin_port = port;

  es_socket (&s1);
  es_reuse (s1);
  es_bind_any (s1);
  es_connect (s1, &in_server);

  s2 = dup (s1);

  FD_ZERO (&rfds); FD_ZERO (&wfds);
  FD_SET (s1, &rfds);
  FD_SET (s2, &wfds);
  if (s1 > max_fd) max_fd = s1;
  if (s2 > max_fd) max_fd = s2;
  printf ("rfds: "); fd_show (&rfds); printf ("\n");
  printf ("wfds: "); fd_show (&wfds); printf ("\n");
  in_rfds = rfds; in_wfds = wfds;
  i = select (FD_SETSIZE, &rfds, &wfds, NULL, NULL);
  if (i < 0)
    {
      perror ("select");
      return 1;
    }
  else
    {
      printf ("i=%d\n", i);
      printf ("rfds: "); fd_show (&rfds); printf ("\n");
      printf ("wfds: "); fd_show (&wfds); printf ("\n");
      if (test)
        {
          if (i != 2 || memcmp (&rfds, &in_rfds, sizeof (rfds)) != 0
              || memcmp (&wfds, &in_wfds, sizeof (wfds)) != 0)
            return 1;
        }
    }
  return 0;
}
