I'm trying to get what I wrote in a child process in a pipe from the parent process, but when I read from the pipe I'm not getting anything, and I don't understand why. I googled a lot for similar problems, and I didn't saw any difference.
Here's a Minimal, Reproducible Example:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#define READ 0
#define WRITE 1
int main(int argc, char **argv) {
pid_t pid = fork();
int fd[2];
char buffer[20];
char message[] = "Hello";
pipe(fd);
if(fd[READ] < 0 || fd[WRITE] < 0){
puts("Pipe creation failed");
return EXIT_FAILURE;
}
if(pid == 0){
/* Child */
close(fd[READ]);
write(fd[WRITE], message, strlen(message));
close(fd[WRITE]);
}else{
/* Parent */
close(fd[WRITE]);
wait(NULL);
read(fd[READ], buffer, 20);
close(fd[READ]);
puts(buffer);
}
return EXIT_SUCCESS;
}