【问题标题】:How can I use C++ to write to an opened terminal?如何使用 C++ 写入已打开的终端?
【发布时间】:2019-02-14 01:51:06
【问题描述】:

我正在尝试与程序 (xfoil) 通信并对其命令行进行读写。 Xfoil 可以在其内置终端中接受许多参数。

我可以使用 system("path") 打开程序,但是如何向打开的 xfoil 终端输入更多命令?一旦我能做到这一点,我就可以用终端命令做所有我需要做的事情。

【问题讨论】:

  • 写入打开的终端很容易(我使用 std::ofstream)。写入在该终端中“运行”的应用程序也很容易,但有所不同。我熟悉的所有替代方案似乎都是 Posix 或 Linux,而不是 C++。我更喜欢posix函数'popen'。它不是 c++ 也不是 c++ 库,而是 Linux 和其他操作系统支持 posix 函数。您还应该研究 Linux fork 和管道,如果您“分叉”一个进程,您可以将输出连接到输入管道,并编写命令,以及通过管道接收反应。这些是 Linux 和 Posix 的一部分,而不是库。
  • 谢谢!

标签: c++ cygwin executable


【解决方案1】:

Tiny Process Library 是一个很好的与进程交互的库。

查看示例 6 和 7,用于向进程发出命令。 https://gitlab.com/eidheim/tiny-process-library/blob/master/examples.cpp

【讨论】:

  • 谢谢你。但是,我试图避免使用库。有没有一种简单的方法来写它而不必包含一个?
【解决方案2】:

如何使用 C++ 写入已打开的终端

在 linux 上,有 7+ 个步骤:

1) 打开一个终端

   I find ctrl-alt t   most convenient
   press and hold ctrl and alt, then press t

   There is also a selection LXTerminal on a mouse menu 

   Note - There is a way for your program to open a 'default' terminal, 
   and c++ can use the technique, but it is not c++, and I always seem to 
   need to change the defaults for my use.  

2) 使用终端,您可以通过以下方式手动查找终端名称:

   type the command "tty" into the terminal

Typical response on my system:

   hostname@username:~$ tty
   /dev/pts/1

在我的 Linux 系统上,终端名称的格式始终为“/dev/pts/x”,其中 x 是一个数字。

3) 对于我的程序(使用第二个终端),我的代码接受(终端响应的)x 部分作为命令参数 1,并使用该参数创建终端的路径文件名 (PFN)。

std::string     aTermPFN    = "/dev/pts/";  // partial address

aTermPFN        += argv[1];  // ouput tty identified by argv[1] 

// creating /dev/pts/<argv[1]>
// thus creating PFN of "/dev/pts/1"

4) 我的代码通常会在创建过程中提供对号码的确认。 (推荐)

std::cout << "accessing '" << aTermPFN 
          << "' with std::ofstream " << std::endl;

5) 然后创建(或尝试创建)ofstream 对象

std::ofstream*  ansiTerm = new std::ofstream(aTermPFN); 

6) 并对其执行一些检查...

if (!ansiTerm->is_open())
{
   std::cerr << "Can not access '" << aTermPFN << "'" << std::endl;
   assert(0); // abort 
}

7) 用完term后,一定要清理

ansiTerm->close(); 
delete ansiTerm;   

// 如果使用适当的智能指针,可以避免删除。

现在到第二个终端的所有输出都使用“ansiTerm”对象,我碰巧在该代码中使用了一个更通用的术语(不是指针,而是引用):“termRef”。

使用示例

// mostly, in the app where these sample exist, I output text at computed
// screen locations

// ansi terminals provide goto row col ansi functions
//   the style is simply position the cursor, 
termRef << m_ansi.gotoRC(3, col) << ss.str() << std::flush;
// then output text-----------------^^^^^^^^ (ss is stringstream)

// ansi terminals can clear 
void clearScr() { termRef << m_ansi.clrscr() << std::flush; }

// ansi terminals can draw simple borders (not-fancy)
{  // across top      gotoRC (int row, int col )
   termRef << m_ansi.gotoRC ( tlcRow, tlcCol+1);
   for   ( int i=0; i<borderWidth; ++i) termRef << m_acs.HLINE;
   termFlush();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多