This code basically a small part of the binary tree with nodes being processes, and it should traverse the tree inorder way passing num1 to left subtree etc. This one just creates a left child and just executes ./tpipe which is the executable of this code again. When we pass it like "./tpipe 0", scanf seems to be getting the input from the user, not the previous processes printfed string. How do I fix this? I should be using dup2 not read write etc since filedp is initated again in the beginning.
This is the cut down version :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "NEED MORE ARGUMENT\n");
return 1;
}
int curDepth = atoi(argv[1]);
int filedp[2];
pipe(filedp);
if (curDepth != 0)
{
char buf[100];
scanf("%s", buf);
fprintf(stderr, "buf is: %s\n", buf);
}
if (curDepth < 1)
{
int fd = fork();
if (fd == 0)
{
close(filedp[0]);
dup2(filedp[1], STDOUT_FILENO);
dup2(filedp[0], STDIN_FILENO);
printf("Example\n");
char *k[] = {"./tpipe", "1", NULL};
execvp("./tpipe", k);
}
else
{
wait(NULL); // parent
}
}
else
{
fprintf(stderr, "IT IS LEAF!\n");
}
return 0;
}
I don't know if I understand it correctly, but it seems like you want the child to read
"Example\n"on its standard input?Then you should write it to the pipe. And you should write that in the parent process: