Skip to content

Instantly share code, notes, and snippets.

@regehr
Created June 25, 2019 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save regehr/fda94b67375352bc3d30ca1d8dcb1ec2 to your computer and use it in GitHub Desktop.
Save regehr/fda94b67375352bc3d30ca1d8dcb1ec2 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void ensure(int x) {
if (!x) {
printf("ensure failed, exiting\n");
exit(-1);
}
}
#define 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