1

My pipe's appear to me to be malfunctioning (although I know I'm doing something wrong). My program 'A1.py' requires input from pipe 'toA1', which it gets fine , it processes the input and sends it's output to 'A2.cpp' via pipe 'toA2'.
'A2.cpp' requires input from pipe 'toA2' and sends its output to the screen (the default stdout).

Once 'A2.cpp' is running via execv(), it still takes input from the user (when it should be taking it from pipe 'toA2'. This is demonstrated by the variable 'use_input' within the second fork. When the following line runs:

std::cout << use_input << std::endl; 

the program prints to the screen "blank", which is what was in the variable "use_input".

I'm not really sure what is going wrong since it works fine for A1.py (the pipe 'toA1' works fine, not sure if it's output to pipe 'toA2' is fine.
I send to stdout in A1.py with 'sys.stdout.write()'.
A3.cpp:

int main(int argc, char **argv) {

pid_t child_pid;
char* empty_arg1[2];
empty_arg1[0] = "A1.py";
empty_arg1[1] = nullptr;
char* empty_arg2[2];
empty_arg2[0] = "A2";
empty_arg2[1] = nullptr;

int toA1[2]; int toA2[2]; pipe(toA1); pipe(toA2);

child_pid = fork();
if (child_pid == 0) {

    dup2(toA1[0], STDIN_FILENO);    //A1 gets stdin from pipe 'toA1'
    close(toA1[0]);
    close(toA1[1]);
    dup2(toA2[1], STDOUT_FILENO); //sends stdout to pipe 'toA2'
    close(toA2[0]);
    close(toA2[1]);

    return execvp("./A1.py", empty_arg1);
}
child_pid = fork();
if (child_pid == 0) {

    std::string use_input = "blank";
    dup2(toA2[0], STDIN_FILENO); //A2 gets stdin from pipe 'toA2'
    close(toA2[0]);
    close(toA2[1]);
    std::cout << "use_input[1] = " << use_input << std::endl;
    return execv("./A2", empty_arg2);
}

dup2(toA2[1], STDOUT_FILENO); //Sends output to 'toA2'
close(toA2[0]);
close(toA2[1]);

while (!std::cin.eof()) {

    getline(std::cin, user_input); 
    std::cout << user_input << std::endl;

}
return 0;
}

A1.py:

def main():

.....

    sys.stdout.write("V " + str(len(vertex_list)) + "\n")
    sys.stdout.write(str_edges + "\n")

if __name__ == '__main__':
main()

Inside A2.cpp, at the start of the file is:

    std::string use_input = "NOPE";
    std::cerr << "A2 is running" << std::endl;
    std::cin >> use_input;
    std::cout << "use_input[2] = " << use_input << std::endl;

When I run my driver program A3.cpp, A3.cpp awaits the user for input "getline(std::cin, user_input);". This passes it to A2.cpp as seen by "std::cin >> use_input;"
Sometimes the pipe from A1 to A2 opens and all the output that A1 has been producing suddenly floods in...and A2.cpp outputs it all onto the screen, when instead it should output the data every ~5 seconds since it is given data once every ~5 seconds Not really sure what the error here is, but I have not been able to figure it out for a few days now. I figure somehow A2.cpp is switching inputs when it should only take input from pipe 'toA2'.

0 Answers0