Hi there,
I am trying to read stdout from a child process to parent using pipe. I am unable to do so. I would appreciate it if someone can point me in the right direction.
Here's my sample program for basic input output:
Code:
#include <stdio.h>
int main()
{
char buffer[10];
printf("first:\n");
fscanf(stdin, "%s", buffer);
FILE *fwriter;
fwriter = fopen("aaa.txt", "w");
fprintf(fwriter, "%s\n", buffer);
fclose(fwriter);
printf("b=%s\n", buffer);
exit(0);
}
Code:
gcc simple.c -o sss
The program that calls fork():
Code:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[50];
int fd[2], fd2[2];
pipe(fd);
pipe(fd2);
pid_t pid = fork();
if(pid == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
dup2(fd2[1], STDOUT_FILENO);
close(fd2[0]);
close(fd2[1]);
execlp("./sss", "./sss", 0);
}
else {
close(fd2[1]);
read(fd2[0], buffer, 50);
printf(buffer);
fgets(buffer, 50, stdin);
/*sprintf(buffer, "%s\n", "doesNotMatter");*/
close(fd[0]);
write(fd[1], buffer, 50);
close(fd[1]);
printf("%s", buffer);
close(fd2[0]);
waitpid(pid, NULL, 0);
}
return 0;
}
The output of tp:
Code:
user1@xmac:~/pipe_test2$ ./tp
123qwe
^C
user1@xmac:~/pipe_test2$
What I would like : I want ./tp to print out "first:" before the prompt for input. Basically, it should emulate ./sss.
Thanks in advance.