/* 
  Copyright 2018-2023 Thorsten Alteholz <libcontra@alteholz.eu>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program (see the file COPYING included with this
  distribution); if not, write to the Free Software Foundation, Inc.,
  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/*!
*************************************************************************
*
* \file libcontra_poll.c
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper for poll()
*
* input/output multiplexing
* man 2 poll
*
*
* \addtogroup libcontra
* The group of the library.
* @{
************************************************************************/

#include <libcontra.h>
#include <libcontra_log.h>
#include <poll.h>

extern bool	libcontra_logPoll; /*!< this is needed to control the output in the logging function */
extern bool	libcontra_isInitialized; /*!< this is needed to control the output in the logging function */

/*!
*************************************************************************
*
* \fn int poll(struct pollfd fds[], nfds_t nfds, int timeout)
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper around libc::poll()
*
* @param[in]  fds     array of file descriptors to look at
* @param[in]  nfds    number of entries in fds array
* @param[in]  timeout wait at least timeout milliseconds for an event to occur
* 
* \return On success, a positive value indicates the total number of file descriptors that have been selected 
*                     0 means timeout for all fds
*         On error, return -1, errno is set
*
************************************************************************/
int poll(struct pollfd fds[], nfds_t nfds, int timeout)
{
  int (*libc_poll)(struct pollfd fds[], nfds_t nfds, int timeout);
  int rc;
  
  if (libcontra_isInitialized==false) {
    libcontra_init();
  } 

  if (libcontra_logPoll) {
    libcontra_log(LOGLEVEL_DEBUG, "D: poll start");
    libcontra_log(LOGLEVEL_INFO,  "I: poll timeout %i\n",timeout);
  }

  *(void **)(&libc_poll) = dlsym(RTLD_NEXT, "poll");
  if(dlerror()) {
    errno = EACCES;
    return -1;
  }

  rc = (*libc_poll)(fds, nfds, timeout);
  
  if (libcontra_logPoll) {
    libcontra_log(LOGLEVEL_INFO, "I: poll rc: %i", rc);
    libcontra_log(LOGLEVEL_DEBUG, "D: poll end");
  }

  return rc;
}

/*! @} */

