|
| 1 | +#ifndef HELPERS_H |
| 2 | +#define HELPERS_H |
| 3 | +#include <unistd.h> |
| 4 | +#include <stdio.h> |
| 5 | +#include <assert.h> |
| 6 | +#include <stdlib.h> |
| 7 | +#include <string.h> |
| 8 | +#include <ctype.h> |
| 9 | +#include <signal.h> |
| 10 | +#include <sys/wait.h> |
| 11 | +#include <sys/time.h> |
| 12 | +#include <sys/select.h> |
| 13 | +#include <sched.h> |
| 14 | +#include <errno.h> |
| 15 | +#include <fcntl.h> |
| 16 | + |
| 17 | +// timestamp() |
| 18 | +// Return the current time as a double. |
| 19 | + |
| 20 | +static inline double timestamp(void) { |
| 21 | + struct timeval tv; |
| 22 | + gettimeofday(&tv, NULL); |
| 23 | + return tv.tv_sec + tv.tv_usec / 1000000.0; |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +// nfork() |
| 28 | +// Like `fork()`, but nondeterministically runs the child first. |
| 29 | +// |
| 30 | +// This is conceptually the same as `fork`, since the OS is allowed to |
| 31 | +// run either process first (or to run them in parallel on multiple |
| 32 | +// cores), but in practice it is rare that the child runs first. This |
| 33 | +// function is useful for shaking out race conditions. |
| 34 | + |
| 35 | +static inline pid_t nfork(void) { |
| 36 | + pid_t p = fork(); |
| 37 | + if (p > 0) { |
| 38 | + struct timeval tv; |
| 39 | + gettimeofday(&tv, NULL); |
| 40 | + if (tv.tv_usec % 7 >= 4) |
| 41 | + usleep(tv.tv_usec % 7); |
| 42 | + } |
| 43 | + return p; |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +// handle_signal(signo, handler) |
| 48 | +// Install `handler` as the signal handler for `signo`. |
| 49 | +// The `handler` is automatically re-installed after signal delivery. |
| 50 | +// Has the same interface as `signal()` (`man 2 signal`), but is portable. |
| 51 | + |
| 52 | +static inline int handle_signal(int signo, void (*handler)(int)) { |
| 53 | + struct sigaction sa; |
| 54 | + sa.sa_handler = handler; // call `handler` on signal |
| 55 | + sigemptyset(&sa.sa_mask); // don't block other signals in handler |
| 56 | + sa.sa_flags = 0; // don't restart system calls |
| 57 | + return sigaction(signo, &sa, NULL); |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +// make_nonblocking(fd) |
| 62 | +// Make file descriptor `fd` nonblocking: attempts to read |
| 63 | +// from `fd` will fail with errno EWOULDBLOCK if no data is |
| 64 | +// available, and attempts to write to `fd` will fail with |
| 65 | +// errno EWOULDBLOCK if no space is available. Not all file |
| 66 | +// descriptors can be made nonblocking, but pipes and network |
| 67 | +// sockets can. |
| 68 | + |
| 69 | +static inline int make_nonblocking(int fd) { |
| 70 | + return fcntl(fd, F_SETFL, O_NONBLOCK); |
| 71 | +} |
| 72 | + |
| 73 | +#endif |
0 commit comments