|
| 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 | + |
| 16 | +// timestamp() |
| 17 | +// Return the current time as a double. |
| 18 | + |
| 19 | +static inline double timestamp(void) { |
| 20 | + struct timeval tv; |
| 21 | + gettimeofday(&tv, NULL); |
| 22 | + return tv.tv_sec + tv.tv_usec / 1000000.0; |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +// nfork() |
| 27 | +// Like `fork()`, but nondeterministically runs the child first. |
| 28 | +// |
| 29 | +// This is actually no different from `fork`, since the OS is allowed to |
| 30 | +// run either process first (or to run them in parallel on multiple |
| 31 | +// cores), but in practice it is rare that the child runs first. This |
| 32 | +// function is useful for shaking out race conditions. |
| 33 | + |
| 34 | +static inline pid_t nfork(void) { |
| 35 | + pid_t p = fork(); |
| 36 | + if (p > 0) { |
| 37 | + struct timeval tv; |
| 38 | + gettimeofday(&tv, NULL); |
| 39 | + if (tv.tv_usec % 7 < 4) |
| 40 | + sched_yield(); |
| 41 | + } |
| 42 | + return p; |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +// handle_signal(signo, handler) |
| 47 | +// Install `handler` as the signal handler for `signo`. |
| 48 | +// The `handler` is automatically re-installed after signal delivery. |
| 49 | +// Has the same interface as `signal()` (`man 2 signal`), but is portable. |
| 50 | + |
| 51 | +static inline int handle_signal(int signo, void (*handler)(int)) { |
| 52 | + struct sigaction sa; |
| 53 | + sa.sa_handler = handler; // call `handler` on signal |
| 54 | + sigemptyset(&sa.sa_mask); // don't block other signals in handler |
| 55 | + sa.sa_flags = 0; // don't restart system calls |
| 56 | + return sigaction(signo, &sa, NULL); |
| 57 | +} |
| 58 | + |
| 59 | +#endif |
0 commit comments