
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

unsigned iterations = 1000;
int ping[2], pong[2];
pid_t pid;

void do_ping (void)
{
    char buffer;
    unsigned i;
    
    for (i = 0; i < iterations; i++) {
        if (write (ping[1], "E", 1) != 1)
            break;
        if (read (pong[0], &buffer, 1) != 1)
            break;
    }

    close (ping[1]);
    close (pong[0]);

    waitpid (pid, &i, 0);
}

void do_echo (void)
{
    char buffer;

    for (;;) {
        if (read (ping[0], &buffer, 1) != 1)
            break;
        if (write (pong[1], "R", 1) != 1)
            break;
    }
}

int main (int argc, char **argv)
{
    if (pipe (ping) == -1 || pipe (pong) == -1)
        return -1;
    
    switch (pid = fork()) {

        case -1:
            return -1;

        case 0:
            close (ping[1]);
            close (pong[0]);
            do_echo();
            return 0;

        default:
            close (ping[0]);
            close (pong[1]);
            do_ping();        
    }

    return 0;
}
