Last active
June 26, 2019 05:36
-
-
Save regehr/02b48aa3cf96df423401b09878bc03b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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