2
#include <stdlib.h>
#include <iostream>
int main(){
system("gnome-terminal");
std::cout<<"something"<<std::cout;
return 0;
}

The above program opens a new terminal and displays "something" message in the old terminal. Is there any way, I could display the "something" in the new terminal.

Note: I am using Linux Ubuntu20.

I am just learning and new to c++, I viewed this but cant get any idea. Please make it as simple as possible. Thanks in advance.

  • 1
    It doesn't work like that. You would have to launch a second executable and let that display its message. And if you want to control one program from another you need other mechanisms like remote procedure calls. – Pepijn Kramer Jan 11 '23 at 10:41
  • Where are you trying to learn C++ from? Learn from a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (not perfect but certainly a lot better then most sites out there). – Pepijn Kramer Jan 11 '23 at 10:43
  • 2
    You can use something like `system("gnome-terminal -- bash -c 'echo something; exec bash -i'")`. This will run the gnome terminal with bash shell inside, and tell the shell to execute an echo command to print 'something', then open the interactive shell with `bash -i`. – Alex Sveshnikov Jan 11 '23 at 11:30

1 Answers1

1

To do this you can mess around with pipes, etc but the easiest way to accomplish this is really open an external file and tail it from within your terminal.

Instead of using std::system I usually prefer to use the boost counterparts to the standard - because they are less regulated and care zero about ABI breaks, they tend to be richer.

The -hold on xterm will prevent the terminal to close.

#include <iostream>
#include <boost/process/child.hpp>
#include <boost/process/io.hpp>

namespace bp = boost::process;

int main() {
    std::ofstream out("/tmp/log.txt");
    bp::child c("xterm -hold -e tail -f /tmp/log.txt");

    for (int j = 0; j < 10; ++j) {
        out << "Hello world!" << std::endl;
        sleep(1);
    }
    c.terminate();
    return 0;
}

enter image description here

Something Something
  • 3,999
  • 1
  • 6
  • 21