Skip to content

Instantly share code, notes, and snippets.

@nnathan
Created December 30, 2023 01:25
Show Gist options
  • Save nnathan/e34dc6ab54784035b85ead0a58045c78 to your computer and use it in GitHub Desktop.
Save nnathan/e34dc6ab54784035b85ead0a58045c78 to your computer and use it in GitHub Desktop.
Ping pong a byte over pipes and measure the exchanges (xv6 1.6 exercise)
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
size_t n_read;
void handle_alarm(int signum) {
printf("n_read = %lu\n", n_read);
fflush(NULL);
n_read = 0;
alarm(1);
}
int main(int argc, char **argv)
{
int p2c[2];
int c2p[2];
n_read = 0;
if (pipe(p2c) == -1) {
perror("pipe");
exit(1);
}
if (pipe(c2p) == -1) {
perror("pipe");
exit(1);
}
pid_t p = fork();
if (p == -1) {
perror("fork");
exit(1);
}
if (p == 0) {
close(p2c[1]);
close(c2p[0]);
signal(SIGALRM, handle_alarm);
alarm(1);
while (1) {
unsigned char c;
if (read(p2c[0], &c, 1) == -1) {
perror("child read");
exit(1);
}
if (write(c2p[1], &c, 1) == -1) {
perror("child write");
exit(1);
}
n_read++;
}
}
unsigned char c = 'X';
signal(SIGALRM, handle_alarm);
alarm(1);
while (1) {
if (write(p2c[1], &c, 1) == -1) {
perror("parent write");
exit(1);
}
if (read(c2p[0], &c, 1) == -1) {
perror("parent read");
exit(1);
}
n_read++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment