💾 Archived View for thrig.me › blog › 2022 › 12 › 11 › withoutblocking.c captured on 2023-06-14 at 15:15:07.
⬅️ Previous capture (2023-04-19)
-=-=-=-=-=-=-
// withoutblocking - run the subsequent program with O_NONBLOCK set on // stdin, e.g. // // make withoutblocking // ./withoutblocking vi #include <sys/wait.h> #include <err.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define TARGET_FD STDIN_FILENO int main(int argc, char *argv[]) { int fd, flags, status; pid_t pid; fd = open("log", O_WRONLY, 0666); pid = fork(); if (pid < 0) err(1, "fork failed"); if (pid == 0) { flags = fcntl(TARGET_FD, F_GETFL, 0); if (flags == -1) err(1, "fcntl getfl failed"); dprintf(fd, "flags init %d\n", flags); flags |= O_NONBLOCK; flags = fcntl(TARGET_FD, F_SETFL, flags); if (flags == -1) err(1, "fcntl setfl failed"); dprintf(fd, "flags before %d\n", flags); argv++; execvp(*argv, argv); err(1, "execvp failed"); } wait(&status); flags = fcntl(TARGET_FD, F_GETFL, 0); if (flags == -1) err(1, "fcntl getfl failed"); dprintf(fd, "flags after %d\n", flags); exit(0); }