Reputation: 55
I am trying to create a two way communication between processes (Parent <---> Child). I writted this code:
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
printf("Program started.");
int p1[2]; // CHILD => PARENT
int p2[2]; // PARENT => CHILD
if (pipe(p1) < 0) {return -1;}
if (pipe(p2) < 0) {return -1;}
int pid = fork();
if (pid == -1) {return -2;}
if (pid == 0)
{//child process
close(p1[0]);
close(p2[1]);
int x;
if (read(p2[0], &x, sizeof(x)) == -1) {return 3;}
printf("Recieved %d\n", x);
x *= x;
if (write(p1[1], &x, sizeof(x)) == -1) {return 4;}
printf("Wrote %d\n", x);
close(p1[1]);
close(p2[0]);
}
else
{//parent process
close(p1[1]);
close(p2[0]);
int y = 7;
if (write(p2[1], &y, sizeof(y) == -1)) {return 5;}
if (read(p1[0], &y, sizeof(y)) == -1) {return 6;}
printf("Result is %d\n", y);
close(p1[0]);
close(p2[1]);
wait(NULL);
}
return 0;
}
This code compiles successfully with gcc on Linux Ubuntu. When i try to run the compiled file, it freezes. The thing that bothers me is that not even the first printf line is executed:
if i comment out either of those two lines, code compiles and executes successfully:
if (pipe(p1) < 0) {return -1;}
if (pipe(p2) < 0) {return -1;}
(The number is not send successfully between the processes becouse there is only one pipe created, but it runs successfully)
What is the problem, and what am i doing wrong? Thanks in advance!
Upvotes: 0
Views: 36
Reputation: 2220
You misplaced a )
here:
if (write(p2[1], &y, sizeof(y) == -1)) {return 5;}
sizeof(y) == -1
evaluates to 0. so you end up with write( ... , ... , 0)
so you write nothing.
Upvotes: 3