Dayrona Dayrona - 9 days ago 5
C Question

How to pipe stdin from child to parent?

I'm trying to

exec()
a child process from a parent process. In this child process, I ask the user to enter a message so it can be printed out by the parent process but I can't find a way to do it...

So far, my code is :

parent.c

int main(int argc, char **argv) {
int fd[2];
char line[80];

pipe(fd);

pid_t pid = (pid_t)fork();

if(pid > 0) {
waitpid(pid, NULL, 0);
close(fd[0]);
int size = read(fd[1], line, 79);
close(fd[1]);
line[size] = '\0';
printf("[parent] Received \"%s\", size = %d\n", line, size);
}
else {
close(fd[1]);
close(stdin);
dup2(fd[0], stdin);
close(fd[0]);
exec("./child", 0, NULL);
}

return 0;
}


child.c

int main(int argc, char **argv) {
char line[80];

printf("[child] Enter message: ");
gets(line, 80);
printf("[child] line = %s\n", line);

return 0;
}


When I launch the parent process, it displays
[child] Enter message:
but when I try to type something, nothing appears, even if I hit the return key.

Do you know how can I make it work ?

Thank you for your help.

Answer

I've found a workaround. My actual goal was to pass information between parent and child. My error was to dup2 on stdin. By doing this, I couldn't enter anything when the program asked. So I passed the value of the file descriptors in the argv and my problem was solved.

Thanks again for your help !