Skip to content

Instantly share code, notes, and snippets.

@regehr regehr/pipe.c
Last active Jun 26, 2019

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void ensure(int x) {
if (x)
return;
printf("ensure failed, exiting\n");
exit(-1);
}
static const int N = 10;
int main(void) {
int pipefd[2];
int res = pipe(pipefd);
ensure(res == 0);
int pid = fork();
ensure(pid >= 0);
if (pid == 0) {
res = close(pipefd[1]);
ensure(res == 0);
int n = 0;
for (int i = 0; i < N; i++) {
char c;
res = read(pipefd[0], &c, 1);
ensure(res == 1);
ensure(c == i + 77);
n++;
}
printf("child process read %d bytes\n", n);
} else {
res = close(pipefd[0]);
ensure(res == 0);
int n = 0;
for (int i = 0; i < N; i++) {
char c = i + 77;
res = write(pipefd[1], &c, 1);
ensure(res == 1);
n++;
}
printf("parent process wrote %d bytes\n", n);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.