I am trying to make a simple fork -> execute another program -> say hello to this child process -> read something -> print received.
The program used as a child simply waits for some input line and prints something to stdout as "hello there!"
This is my "host" program (which does not work):
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #define IN 0 #define OUT 1 #define CHILD 0 main () { pid_t pid; int pipefd[2]; FILE* output; char buf[256]; pipe(pipefd); pid = fork(); if (pid == CHILD) { printf("child\n"); dup2(pipefd[IN], IN); dup2(pipefd[OUT], OUT); execl("./test", "test", (char*) NULL); } else { sleep(1); printf("parent\n"); write(pipefd[IN], "hello!", 10); // write message to the process read(pipefd[OUT], buf, sizeof(buf)); printf("received: %s\n", buf); } }
I get this:
child [.. waits 1 second ..] parent received:
What am I missing? Thanks!
EDIT (test.c):
On request, this is a child program:
#include <stdio.h> #include <string.h> #include <stdlib.h> int getln(char line[]) { int nch = 0; int c; while((c = getchar()) != EOF) { if(c == '\n') break; line[nch] = c; nch++; } if(c == EOF && nch == 0) return EOF; return nch; } main() { char line[20]; getln(line); printf("hello there!", line); fflush(stdout); return 0; }
source share