Un_known_user
Un_known_user

Reputation: 39

C++ Program to open a new Terminal and display something in the new Terminal

#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.

Upvotes: 2

Views: 416

Answers (1)

Henrique Bucher
Henrique Bucher

Reputation: 4474

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

Upvotes: 1

Related Questions