Unix / C ++:打开新终端并将输出重定向到它 [英] Unix/C++: Open new terminal and redirect output to it
问题描述
我的程序(Solaris 10上的C ++)从shell启动时,通过wcout将输出写入其终端。但是当我在Sun Studio中执行它时,或者文件管理器没有终端,输出将出现在Sun Studio输出窗口或者根本没有。
My program (C++ on Solaris 10) writes output via wcout to its terminal when it is started from a shell. But when I execute it from within Sun Studio or the file manager is does not have a terminal and the ouput appears in the Sun Studio output window or nowhere at all.
希望它在三种情况中的任何一种情况下打开自己的终端窗口,并将wcout附加到此终端窗口。我想这是做程序本身与C ++系统调用,而不是通过某种方式如何从一些shell或脚本执行程序。因为然后在Studio IDE中执行并在文件管理器中双击仍然会有相同的效果。
I would like it to open its own terminal window in any of the three cases and attach wcout to this terminal window. I want this to be done be the program itself with C++ system calls not by the way how the program is executed from some shell or script. Because then execution in the Studio IDE and double-click in the file manager would still have the same effect.
作为一个Windows程序员,我觉得很自然,没有找到这是如何做在我的Unix书籍或在网络。
Being a Windows programmer that seems quite natural to me but I could not find out how this is done in my Unix books nor in the web. Am I requesting the wrong thing, is it really so hard to do or am I missing something?
推荐答案
以下是接近于你要什么。它仍然有一些错误:
The following is close to what you want. It still has a few bugs:
- xterm不能正常关闭(当程序终止时关闭)。我不知道为什么会这样。
- 在输出之前,输出一个数字。再次,我不知道为什么。
- 我似乎无法重定向输入。
也许别人知道如何修复这些错误(以及任何其他我可能没有注意到的)。
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;
}
这篇关于Unix / C ++:打开新终端并将输出重定向到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!