Redirecting stdout with execvp

29 Views Asked by At

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;
}
1

There are 1 best solutions below

5
Some programmer dude On

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:

if (fd == 0)
{
    // Child process

    close(filedp[1]);  // We don't need the write-end of the pipe here

    dup2(filedp[0], STDIN_FILENO);  // Copy the read-end of the pipe to standard input

    // Then execute the program
    char *k[] = {"./tpipe", "1", NULL};
    execvp("./tpipe", k);
}
else
{
    // Parent process

    close(filedp[0]);  // We don't need the read-end of the pipe here

    write(filedp[1], "Example\n", 8);  // Write to the pipe
    // The child process will read the above from its standard input

    // Wait for the child process to exit
    wait(NULL);
}