summaryrefslogtreecommitdiff
path: root/otherlibs/unix/sleep.c
blob: 4a8339608522789aabfa496d823b01f500b7af2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/***********************************************************************/
/*                                                                     */
/*                                OCaml                                */
/*                                                                     */
/*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         */
/*                                                                     */
/*  Copyright 1996 Institut National de Recherche en Informatique et   */
/*  en Automatique.  All rights reserved.  This file is distributed    */
/*  under the terms of the GNU Library General Public License, with    */
/*  the special exception on linking described in file ../../LICENSE.  */
/*                                                                     */
/***********************************************************************/

#include <caml/mlvalues.h>
#include <caml/signals.h>
#include "unixsupport.h"

#include <errno.h>
#include <time.h>
#ifdef HAS_SELECT
#include <sys/types.h>
#include <sys/time.h>
#ifdef HAS_SYS_SELECT_H
#include <sys/select.h>
#endif
#endif

CAMLprim value unix_sleep(value duration)
{
  double d = Double_val(duration);
  if (d <= 0.0) return Val_unit;
#if _POSIX_C_SOURCE >= 199309L
  {
    struct timespec t;
    int ret;
    enter_blocking_section();
    t.tv_sec = (time_t) d;
    t.tv_nsec = (d - t.tv_sec) * 1e9;
    do {
      ret = nanosleep(&t, &t);
    } while (ret == -1 && errno == EINTR);
    leave_blocking_section();
    if (ret == -1) uerror("sleep", Nothing);
  }
#elif defined(HAS_SELECT)
  {
    struct timeval t;
    int ret;
    enter_blocking_section();
    t.tv_sec = (time_t) d;
    t.tv_usec = (d - t.tv_sec) * 1e6;
    do {
      ret = select(0, NULL, NULL, NULL, &t);
    } while (ret == -1 && errno == EINTR);
    leave_blocking_section();
    if (ret == -1) uerror("sleep", Nothing);
  }
#else
  /* Fallback implementation, resolution 1 second only.
     We cannot reliably iterate until sleep() returns 0, because the
     remaining time returned by sleep() is generally rounded up. */
  {
    enter_blocking_section();
    sleep ((unsigned int) d);
    leave_blocking_section();
  }
#endif
  return Val_unit;
}