Unix/C++: Open new terminal and redirect output to it Unix/C++: Open new terminal and redirect output to it unix unix

Unix/C++: Open new terminal and redirect output to it


The following is close to what you want. It still has a few bugs:

  • The xterm cannot be normally closed (it closes when the program terminates, though). I have no idea why this is so.
  • Before the intended output, a number is output. Again, I have no idea why.
  • I don't seem to be able to redirect input.

Maybe someone else know how to fix those bugs (and any others I might not have noticed).

#include <stdlib.h>#include <fcntl.h>#include <string.h>#include <unistd.h>#include <iostream>#include <sstream>int main(){  int pt = posix_openpt(O_RDWR);  if (pt == -1)  {    std::cerr << "Could not open pseudo terminal.\n";    return EXIT_FAILURE;  }  char* ptname = ptsname(pt);  if (!ptname)  {    std::cerr << "Could not get pseudo terminal device name.\n";    close(pt);    return EXIT_FAILURE;  }  if (unlockpt(pt) == -1)  {    std::cerr << "Could not get pseudo terminal device name.\n";    close(pt);    return EXIT_FAILURE;  }  std::ostringstream oss;  oss << "xterm -S" << (strrchr(ptname, '/')+1) << "/" << pt << " &";  system(oss.str().c_str());  int xterm_fd = open(ptname,O_RDWR);  char c;  do read(xterm_fd, &c, 1); while (c!='\n');  if (dup2(pt, 1) <0)  {    std::cerr << "Could not redirect standard output.\n";    close(pt);    return EXIT_FAILURE;  }  if (dup2(pt, 2) <0)  {    std::cerr << "Could not redirect standard error output.\n";    close(pt);    return EXIT_FAILURE;  }  std::cout << "This should appear on the xterm." << std::endl;  std::cerr << "So should this.\n";  std::cin.ignore(1);  close(pt);  return EXIT_SUCCESS;}


You want to output to a file (redirect, using a logging API or close stdout/reopen it as a file). And then tail it with tail -f in a terminal of your choice.

This has added benefit of saving your log output for review even if the terminal crashes/is killed.


When you invoke your program, instead of running: myprog 1 2 3 a b c, run xterm -e myprog 1 2 3 a b c.