💾 Archived View for thrig.me › blog › 2024 › 01 › 18 › bufferblock.c captured on 2024-02-05 at 10:55:28.

View Raw

More Information

-=-=-=-=-=-=-

#include <sys/wait.h>
#include <err.h>
#include <stdio.h>
#include <unistd.h>

#define ALOT 1024
#define CHILD 0
#define PIPE_READER 0
#define PIPE_WRITER 1
// the limit for my OpenBSD 7.4 system (AMD64) is just below this
#define TOPRINT 16385

char buf[ALOT];

int main(void) {
	int bpipe[2], status;
	pid_t pid;
	size_t amount = 0, counter = 0;
	if (pipe(bpipe) == -1) err(1, "pipe");
	pid = fork();
	if (pid < 0) err(1, "fork");
	if (pid == CHILD) {
		// wire up stdin to the pipe (only really needed if you
		// were to exec off to some other program)
		close(bpipe[PIPE_WRITER]);
		if (dup2(bpipe[PIPE_READER], STDIN_FILENO) != STDIN_FILENO)
			err(1, "dup");
		close(bpipe[PIPE_READER]);
		while (1) {
			fprintf(stderr, "child waiting... %zu\n", counter++);
			sleep(1);
		}
		errx(1, "fell off the loop??");
	}
	close(bpipe[PIPE_READER]);
	while (amount < TOPRINT) {
		write(bpipe[PIPE_WRITER], buf, ALOT);
		amount += ALOT;
	}
	while (1) {
		fprintf(stderr, "parent waiting... %zu\n", counter++);
		waitpid(pid, &status, WNOHANG);
		sleep(1);
	}
	errx(1, "child went away??");
}