#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
int func(int pipefd[]) {
char buffer[128];
pid_t pid;
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
close(pipefd[1]);
ssize_t count = read(pipefd[0], buffer, sizeof(buffer));
if (count == -1) {
perror("read");
return 1;
}
buffer[count] = '\0';
std::cout << "Child process received: " << buffer << std::endl;
close(pipefd[0]);
} else {
close(pipefd[0]);
const char* msg = "Hello from parent process!";
write(pipefd[1], msg, strlen(msg));
close(pipefd[1]);
wait(NULL);
}
return 0;
}
int main() {
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
int res = func(pipefd);
std::cout << "res: " << res << std::endl;
int pipefd2[2];
if (pipe(pipefd2) == -1) {
perror("pipe");
return 1;
}
res = func(pipefd2);
std::cout << "res: " << res << std::endl;
return 0;
}