54 lines
1.3 KiB
C
54 lines
1.3 KiB
C
//
|
|
// Written for Computer Networks and Systems lab classes
|
|
// AUTHOR : Sergiusz Warga
|
|
|
|
#include <fcntl.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
void echo(int parent_to_child, int child_to_parent) {
|
|
while(1) {
|
|
char buff[8000] = {0};
|
|
int read_bytes = read(parent_to_child, &buff, sizeof(buff));
|
|
write(child_to_parent, &buff, read_bytes);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
int parent_to_child[2], child_to_parent[2];
|
|
if (pipe(parent_to_child) < 0 || pipe(child_to_parent) < 0 ){
|
|
fprintf(stderr,"Something went wrong!\n");
|
|
return -1;
|
|
}
|
|
|
|
int status;
|
|
pid_t pid;
|
|
pid = fork();
|
|
|
|
if (pid == -1) { // If something went wrong.
|
|
perror("Fork: ");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
if (pid == 0) { // If this is a child process.
|
|
echo(parent_to_child[0], child_to_parent[1]);
|
|
exit(EXIT_SUCCESS);
|
|
}
|
|
|
|
char buff[8000];
|
|
char messages[3][32] = {"Hello there!", "Second message.", "Bye!"};
|
|
|
|
for (int i = 0; i < 3; ++i) {
|
|
write(parent_to_child[1], &messages[i], sizeof(messages[i]));
|
|
read(child_to_parent[0], buff, sizeof(buff));
|
|
printf("%s\n", buff);
|
|
}
|
|
|
|
wait(&status);
|
|
close(parent_to_child[1]);
|
|
close(child_to_parent[0]);
|
|
|
|
return 0;
|
|
} |