Dayrona Dayrona - 1 year ago 67
C Question

How to pipe stdin from child to parent?

I'm trying to

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 :


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


pid_t pid = (pid_t)fork();

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

return 0;


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 Source

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 !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download