Timo
Timo

Reputation: 9835

Open Terminal/Console and bind stdout to it from C++ on macOS

I have a shared library that gets loaded as a plugin from a third party application and I want to open a terminal/console window to see what gets written to stdout during debugging. On Windows I use Visual C++ Enable Console to enable and bind the console. Now I want to do the same for macOS, how would I do that?

Upvotes: 1

Views: 435

Answers (1)

Botje
Botje

Reputation: 30850

You can spawn Terminal.app with a shell script you specify. So:

// Redirect stdout and stderr to a new temp file
char template[] = "/tmp/command_output_XXXXXX";
int fd = mkstemp(template);
dup2(fd, 1);
dup2(fd, 2);

// Prepare script
std::string command(template);
command += ".sh";

std::ofstream out(command);
out << "#!/bin/sh" << std::endl;
out << "exec /usr/bin/tail -f " << template << std::endl;
out.close();

// and go
std::stringstream ss;
ss << "open -a Terminal.app " << command;
system(ss.str().c_str());

Upvotes: 1

Related Questions