#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
int parent(int input, int output)
{
char buffer[1024];
int result;
while((result = read(0, buffer, 1024)) > 0)
{
if(write(output, buffer, result) != result)
{
perror("Error writing to pipe");
return 5;
}
if(read(input, buffer, result) != result)
{
perror("Error reading from pipe");
return 4;
}
if(write(1, buffer, result) != result)
{
perror("Error writing to standard output");
return 7;
}
}
if(result != 0)
{
perror("Error reading from standard input");
return 6;
}
return 0;
}
int child(int input, int output)
{
char buffer[1024];
int result;
while((result = read(input, buffer, 1024)) > 0)
{
for(int i=0; i!=result; ++i)
buffer[i] = toupper(buffer[i]);
if(write(output, buffer, result) != result)
{
perror("Error writing to pipe");
return 5;
}
}
if(result != 0)
{
perror("Error reading from pipe");
return 4;
}
return 0;
}
int call_parent(int parent_to_child[2], int child_to_parent[2])
{
close(child_to_parent[1]);
close(parent_to_child[0]);
return parent(child_to_parent[0], parent_to_child[1]);
}
int call_child(int parent_to_child[2], int child_to_parent[2])
{
close(parent_to_child[1]);
close(child_to_parent[0]);
return child(parent_to_child[0], child_to_parent[1]);
}
int main(void)
{
puts("Write some ASCII text");
int parent_to_child[2];
if(pipe(parent_to_child) == -1)
{
perror("Error creating pipe from parent to child");
return 1;
}
int child_to_parent[2];
if(pipe(child_to_parent) == -1)
{
perror("Error creating pipe from child to parent");
return 2;
}
switch(fork())
{
case -1: perror("Fork failed"); return 3;
case 0: return call_child(parent_to_child, child_to_parent);
default: return call_parent(parent_to_child, child_to_parent);
}
return 0;
}