I'm trying to write a program that allows a process to 2-way communicate to its child, i.e. it can send a message to and also receive a message from the child. My first attempt to create 2 pipes and link each end of the pipes to the parent and child stdin and stdout:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int firstPipe[2];
int secondPipe[2];
if (pipe(firstPipe) < 0) {
perror("pipe");
exit(1);
}
if (pipe(secondPipe) < 0) {
perror("pipe");
exit(1);
}
if (fork() != 0) { // child
dup2(firstPipe[0], 0);
dup2(secondPipe[1], 1);
char input[70];
printf("Mr. Stark...");
fgets(input, 70, stdin);
fprintf(stderr, "%s I don't wanna go...\n", input);
} else { // parent
dup2(secondPipe[0], 0);
dup2(firstPipe[1], 1);
char message[70];
fgets(message, 70, stdin);
printf("%s I don't feel so good...", message);
}
return 0;
}
This program is supposed to send a message from the child to the parent, then the parent sends a reply to the child, and then the child prints the final result (Mr. Stark... I don't feel so good... I don't wanna go...) to stderr, but it's not working :( When I try to run it, it freezes as if one of the processes (or both of them) is waiting for an input. Is there something wrong with my code? I'm open for suggestions of other approaches as well, as long as the final result works. Thanks for you help.
fgets
reads until it sees a newline (or the buffer is full).
The parent starts out with
fgets(message, 70, stdin);
waiting for a line.
The child outputs
printf("Mr. Stark...");
then also waits:
fgets(input, 70, stdin);
"Mr. Stark..."
does not contain a newline. In fact, it's probably not being sent at all and instead buffered inside of stdout
, but that could be fixed with fflush(stdout)
after printf
.
But even then, fgets
would still be waiting for a newline that never comes.
Fix:
printf("Mr. Stark...\n");
fflush(stdout);