I want to read the integer from the pipe and then print it, but everytime it prints garbage value. Someone that can help me out?
int main()
{
int pid1 = fork();
int fd1[2];
pipe(fd1);
if (pid1 == 0) // Child process
{
int x;
close(fd1[1]);
read(fd1[0], &x, sizeof(int));
printf("I'm the First Child and I received: %d\n", x); // <--- Here it prints garbage value
close(fd1[0]);
}
else // Parent process
{
int x = 5;
close(fd1[0]);
write(fd1[1], &x, sizeof(int));
close(fd1[1]);
}
}
I had to fork()
after creating the pipes. So the code looks like this:
int main()
{
int fd1[2];
pipe(fd1);
int pid1 = fork();
if (pid1 == 0) // Child process
{
int x;
close(fd1[1]);
read(fd1[0], &x, sizeof(int));
printf("I'm the First Child and I received: %d\n", x);
close(fd1[0]);
}
else // Parent process
{
int x = 5;
close(fd1[0]);
write(fd1[1], &x, sizeof(int));
close(fd1[1]);
}
}