+
+PUBLIC_FN void *mmap_file(void *addr, size_t length, int prot, int flags, char *path, off_t offset) {
+ assert((flags&MAP_ANONYMOUS) == 0);
+ assert(prot&(PROT_EXEC|PROT_READ|PROT_WRITE));
+ int open_flags = O_CLOEXEC;
+ if ((prot & (PROT_READ|PROT_EXEC)) && !(prot&PROT_WRITE)) open_flags |= O_RDONLY;
+ else if ((prot & (PROT_READ|PROT_EXEC))) open_flags |= O_RDWR;
+ else open_flags |= O_WRONLY;
+ int fd = open(path, open_flags);
+ if (fd == -1) return NULL;
+ void *r = mmap(addr, length, prot, flags, fd, offset);
+ int errno_ = errno;
+ close(fd);
+ errno = errno_;
+ return (r==MAP_FAILED) ? NULL : r;
+}
+
+// on error, fd remains unchanged, no matter whether you specified "keep" or not
+HEADER #define JH_OBS_KEEPFD 1
+HEADER #define JH_OBS_BUFFER 2
+PUBLIC_FN int fopen_bistream(FILE **in, FILE **out, int fd, int flags) {
+ // check input
+ if (fd < 0) goto err_out;
+ bool keep = flags & JH_OBS_KEEPFD;
+ bool buffer = flags & JH_OBS_BUFFER;
+
+ // create input FILE*
+ int in_fd = dup(fd);
+ if (in_fd < 0) goto err_out;
+ *in = fdopen(in_fd, "r");
+ if (!*in) { close(in_fd); goto err_out; }
+
+ // create output FILE*
+ int out_fd = keep ? dup(fd) : fd;
+ if (out_fd < 0) goto err_dup_out;
+ *out = fdopen(out_fd, "w");
+ if (!*out) { if (keep) close(out_fd); goto err_dup_out; }
+
+ // avoid buffering data unless the caller really wants it
+ if (!buffer) setbuf(*out, NULL);
+
+ // success!
+ return 0;
+
+
+err_dup_out:
+ fclose(*in);
+err_out:
+ return EAI_SYSTEM;
+}
\ No newline at end of file