Created
June 25, 2019 17:28
-
-
Save regehr/fda94b67375352bc3d30ca1d8dcb1ec2 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> | |
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