#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int fd1[2], fd2[2]; // fd1: parent->child, fd2: child->parent
int result;
char buffer[100];
ssize_t size;
if (pipe(fd1) < 0 || pipe(fd2) < 0) {
printf("Can't create pipe\n");
exit(1);
}
result = fork();
if (result < 0) {
printf("Can't fork child\n");
exit(1);
}
else if (result > 0) { // Родитель
close(fd1[0]); // не читаем из fd1
close(fd2[1]); // не пишем в fd2
write(fd1[1], "Hello from parent", 18);
size = read(fd2[0], buffer, sizeof(buffer) - 1);
buffer[size] = '\0';
printf("Parent received: %s\n", buffer);
close(fd1[1]);
close(fd2[0]);
}
else { // Ребёнок
close(fd1[1]); // не пишем в fd1
close(fd2[0]); // не читаем из fd2
size = read(fd1[0], buffer, sizeof(buffer) - 1);
buffer[size] = '\0';
printf("Child received: %s\n", buffer);
write(fd2[1], "Hello from child", 17);
close(fd1[0]);
close(fd2[1]);
}
return 0;
}