/*****************************************************************************\
* Copyright (c) 2004 Pelle Johansson.                                         *
* All rights reserved.                                                        *
*                                                                             *
* This file is part of the moftpd package. Use and distribution of            *
* this software is governed by the terms in the file LICENCE, which           *
* should have come with this package.                                         *
\*****************************************************************************/

/* $moftpd: events_kqueue.c 1251 2005-03-06 22:24:29Z morth $ */

#include "system.h"

#include "events.h"

static int kq;

void events_einit (void)
{
  kq = kqueue ();
}

int events_earf (int fd, void *data)
{
  struct kevent ev;
  struct timespec t = {0};
  
  EV_SET (&ev, fd, EVFILT_READ, EV_ADD, 0, 0, data);
  
  return kevent (kq, &ev, 1, NULL, 0, &t);
}

int events_eawf (int fd, void *data)
{
  struct kevent ev;
  struct timespec t = {0};
  
  EV_SET (&ev, fd, EVFILT_WRITE, EV_ADD, 0, 0, data);
  
  return kevent (kq, &ev, 1, NULL, 0, &t);
}

void events_errf (int fd)
{
  struct kevent ev;
  struct timespec t = {0};
  
  EV_SET (&ev, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
  
  kevent (kq, &ev, 1, NULL, 0, &t);
}

void events_erwf (int fd)
{
  struct kevent ev;
  struct timespec t = {0};
  
  EV_SET (&ev, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
  
  kevent (kq, &ev, 1, NULL, 0, &t);
}

int run_events (void)
{
  struct kevent evs[10];
  int res, i;
  struct timespec t;
  
  t.tv_sec = 10;
  t.tv_nsec = 0;
  
  res = kevent (kq, NULL, 0, evs, 10, &t);
  if (res < 0)
  {
    if (errno == EINTR)
      return 0;
    return res;
  }
  
  for (i = 0; i < res; i++)
  {
    if (events_run_data (evs[i].udata, 0)) // TODO urgent?
      break;
  }
  return 0;
}


syntax highlighted by Code2HTML, v. 0.9.1