cscg24-guacamole

CSCG 2024 Challenge 'Guacamole Mashup'
git clone https://git.sinitax.com/sinitax/cscg24-guacamole
Log | Files | Refs | sfeed.txt

wait-fd.c (2011B)


      1/*
      2 * Licensed to the Apache Software Foundation (ASF) under one
      3 * or more contributor license agreements.  See the NOTICE file
      4 * distributed with this work for additional information
      5 * regarding copyright ownership.  The ASF licenses this file
      6 * to you under the Apache License, Version 2.0 (the
      7 * "License"); you may not use this file except in compliance
      8 * with the License.  You may obtain a copy of the License at
      9 *
     10 *   http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing,
     13 * software distributed under the License is distributed on an
     14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     15 * KIND, either express or implied.  See the License for the
     16 * specific language governing permissions and limitations
     17 * under the License.
     18 */
     19
     20#include "config.h"
     21
     22#ifdef ENABLE_WINSOCK
     23#    include <winsock2.h>
     24#else
     25#    ifdef HAVE_POLL
     26#        include <poll.h>
     27#    else
     28#        include <sys/select.h>
     29#    endif
     30#endif
     31
     32#ifdef HAVE_POLL
     33int guac_wait_for_fd(int fd, int usec_timeout) {
     34
     35    /* Initialize with single underlying file descriptor */
     36    struct pollfd fds[1] = {{
     37        .fd      = fd,
     38        .events  = POLLIN,
     39        .revents = 0
     40    }};
     41
     42    /* No timeout if usec_timeout is negative */
     43    if (usec_timeout < 0)
     44        return poll(fds, 1, -1);
     45
     46    /* Handle timeout if specified, rounding up to poll()'s granularity */
     47    return poll(fds, 1, (usec_timeout + 999) / 1000);
     48
     49}
     50#else
     51int guac_wait_for_fd(int fd, int usec_timeout) {
     52
     53    fd_set fds;
     54
     55    /* Initialize fd_set with single underlying file descriptor */
     56    FD_ZERO(&fds);
     57    FD_SET(fd, &fds);
     58
     59    /* No timeout if usec_timeout is negative */
     60    if (usec_timeout < 0)
     61        return select(fd + 1, &fds, NULL, NULL, NULL); 
     62
     63    /* Handle timeout if specified */
     64    struct timeval timeout = {
     65        .tv_sec  = usec_timeout / 1000000,
     66        .tv_usec = usec_timeout % 1000000
     67    };
     68
     69    return select(fd + 1, &fds, NULL, NULL, &timeout);
     70
     71}
     72#endif