1

Basically I created a shell and I want to using the Google Unit Test to test if my shell does the something of the regular terminal, and I am wondering how can I copy the output of my shell output into a string and compare it. Simply, I have created a buffer which reads the output of a regular terminal, and I don't know how to use a buffer to read my shell output. Here is my code for the Google Unit Test

TEST(lsTest, lsT) {
    string bash_cmd = "ls";
    std::array<char, 128> buffer;
    string result;
    FILE* pipe = popen(bash_cmd.c_str(),"r");
    while(fgets(buffer.data(),128,pipe)!=NULL){
            result += buffer.data();
    }
    Base* start = parse(bash_command); 
    start->execute(); // this would output the command of my shell
    EXPECT_EQ(result,?output of start->execute()?);}

Since the execute() is a boolean function, I can't using the buffer to convert the output to a string. Is there any way to read to output of my shell into a string? Also, my shell doesn't contains any redirection which are >, >>,| tee, etc. It basically contains ls, echo,mkdir.

Chris Lo
  • 11
  • 1
  • How does your shell prints output? Does it use `std::cout` or `write(STDOUT_FILENO, ...)` or `printf`? Does it also uses `std::cerr` or `write(STDERR_FILENO, ...)` or `fprintf(stderr, ...)`? – KamilCuk Nov 21 '18 at 08:13
  • If it uses `std::cout` or standard C++ output ostreams, you can use asnwer from [this thread](https://stackoverflow.com/questions/37758378/swapping-a-stringstream-for-cout). – KamilCuk Nov 21 '18 at 08:24
  • It is using the execvp(). – Chris Lo Nov 21 '18 at 10:25
  • `execvp`. Ok, so you can only guess what output does the underlying command uses. So, what you need to do, is redirect `STDOUT_FILENO` into a `stringstream` and parse it. Create a `mkfifo` and then `dup2(fifo, STDOUT_FILENO)` and make sure to read from fifo into `strngstream` in another thread while the `ls` command is executing. In other words, you need to do similar as shell redirecters commands stdout like `ls > buffer`, only the buffer should be a stringstream or similar container. – KamilCuk Nov 21 '18 at 10:27
  • with popen() you will get the stdout of your script - but you won't get eventual errors to stderr. See this https://stackoverflow.com/questions/6900577/c-popen-wont-catch-stderr – Sigi Nov 21 '18 at 10:34
  • @KamilCuk It would be nice if you could simply write me some code of what you are implying since I am not really familiar with that. – Chris Lo Nov 21 '18 at 12:31
  • In the link i've posted there's [this answer](https://stackoverflow.com/a/5419409/9072753) which even a ready to use class. Maybe it will make you understand it better. – KamilCuk Nov 21 '18 at 12:45

0 Answers0