将字符发送到控制台应用程序

问题描述:

我有一个在终端窗口中运行的简单控制台应用程序读取和打印字符:

I have simple console application that runs in terminal window reads and prints character:

int main(int argc, char **argv, char **envp)
{
    while (true)
    {
        char c =getchar();
        printf("%c \n",c);

    }

}

现在我想做一个可以在第一个应用程序终端中模拟字符按下的测试应用程序.

Now I would like to make test application that could emulate character press in first application terminal.

我该走哪条路?为此,我应该使用哪些 API 函数?

Which way I should go? What API functions I should use for this purpose?

不需要特殊的 API 或其他任何东西.由于您的示例应用程序仅从标准输入中读取数据,因此您可以将内容发送到那里.

No need for special APIs or whatever. Since your sample application is only reading from standard input, you can just send stuff to there.

在终端中运行程序之前,使用 tty 命令检查其连接的终端.然后将数据发送到 tty 报告的 tty.

Before running the program in a terminal, check its connected terminal using tty command. Then send data to that tty that tty reports.

或者,获取正在运行的应用程序的 PID 并将数据发送到 /proc/$PID/fd/0,这样您就不需要检查 tty.

Alternatively, grab the PID of your running application and send data to /proc/$PID/fd/0 so you don't need to check for tty.