将来自 stdin 的交互式输入与到 stdout 的异步输出相结合
Combine interactive input from stdin with async output to stdout
我的测试应用程序在 stderr
中写入日志并使用 stdin
接收来自用户的交互式命令。不用说,任何 stderr
输出都会破坏终端中的用户输入(和命令提示符)。例如这个命令行(_
是光标位置):
Command: reboo_
将变为:
Command: reboo04-23 20:26:12.799 52422 2563 D run@main.cpp:27 started
_
在 log()
调用之后。
为了解决这个问题,我想在终端中使用类似旧版 Quake 控制台的东西,日志在当前输入行上方一行。换句话说,我想得到它:
04-23 20:26:12.799 52422 2563 D run@main.cpp:27 started
Command: reboo_
我可以修改日志记录代码和读取用户输入的代码。希望它适用于 Linux 和 OS X。可以从不同的线程调用 log()
函数。 log()
函数是 stderr
的唯一写入器。
欢迎提出解决该问题(损坏的输入行)的其他建议。我正在寻找无需额外库(如 Curses)即可实施的解决方案。我试图 google 向上,但意识到我需要一种惯用的开场白来理解我到底想要什么。
更新
感谢 Jonathan Leffler 的评论,我意识到我还应该提到 separating stderr
和 stdout
没那么重要。因为我控制了 log()
函数,所以让它写入 stdout
而不是 stderr
不是问题。不过不确定它是否使任务更容易。
更新
精心制作了一些看起来效果不错的东西:
void set_echoctl(const int fd, const int enable)
{
struct termios tc;
tcgetattr(fd, &tc);
tc.c_lflag &= ~ECHOCTL;
if (enable)
{
tc.c_lflag |= ECHOCTL;
}
tcsetattr(fd, TCSANOW, &tc);
}
void log(const char *const msg)
{
// Go to line start
write(1, "\r", 1);
// Erases from the current cursor position to the end of the current line
write(1, "3[K", strlen("3[K"));
fprintf(stderr, "%s\n", msg);
// Move cursor one line up
write(1, "3[1A", strlen("3[1A"));
// Disable echo control characters
set_echoctl(1, 0);
// Ask to reprint input buffer
termios tc;
tcgetattr(1, &tc);
ioctl(1, TIOCSTI, &tc.c_cc[VREPRINT]);
// Enable echo control characters back
set_echoctl(1, 1);
}
但是,它不支持命令提示符("Command: " 在输入行的开头)。但也许我可以为此设置两行 - 一行用于命令提示符,另一行用于输入本身,例如:
Command:
reboo_
这是我做的事情。打开 3 个控制台:
Console #1:(运行程序,输入std::cin)
> ./program > output.txt 2> errors.txt
控制台 #2:(视图 std::cout)
> tail -f output.txt
控制台 #3:(视图 std::cerr)
> tail -f errors.txt
任何程序输入都输入到控制台:#1。
您可以获得一些控制台,例如 Terminator
,允许您将屏幕分成不同的部分:
根据对您可能想使用 readline 库查看的问题的更新:
它将用户输入的底线分开,并将所有内容输出到它上面的线。它还提供了一个可配置的提示符,甚至具有记录输入历史的功能。
下面是一个示例,您可以从中获得灵感来构建 log()
函数:
#include <cstdlib>
#include <memory>
#include <iostream>
#include <algorithm>
#include <readline/readline.h>
#include <readline/history.h>
struct malloc_deleter
{
template <class T>
void operator()(T* p) { std::free(p); }
};
using cstring_uptr = std::unique_ptr<char, malloc_deleter>;
std::string& trim(std::string& s, const char* t = " \t")
{
s.erase(s.find_last_not_of(t) + 1);
s.erase(0, s.find_first_not_of(t));
return s;
}
int main()
{
using_history();
read_history(".history");
std::string shell_prompt = "> ";
cstring_uptr input;
std::string line, prev;
input.reset(readline(shell_prompt.c_str()));
while(input && trim(line = input.get()) != "exit")
{
if(!line.empty())
{
if(line != prev)
{
add_history(line.c_str());
write_history(".history");
prev = line;
}
std::reverse(line.begin(), line.end());
std::cout << line << '\n';
}
input.reset(readline(shell_prompt.c_str()));
}
}
这个简单的例子只是反转你在控制台输入的所有内容。
以下是我想出的最终解决方案。它实际上是一个生成 N 个线程并从每个线程发出日志的工作示例。同时允许交互式用户输入命令。不过,唯一受支持的命令是 "exit"。其他命令将被静默忽略。它有两个小缺陷(就我而言)。
首先一个是命令提示符必须在单独的一行上。像那样:
Command:
reboo_
原因是 VREPRINT
控制字符也发出一个新行。所以我没有找到如何在没有新行的情况下重新打印当前输入缓冲区的方法。
Second 是在打印日志行的同时输入符号时偶尔出现的闪烁。但是尽管闪烁,最终结果是一致的,并且没有观察到线条重叠。也许以后我会想办法避免它,让它变得光滑干净,但已经足够好了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/termios.h>
#include <sys/ioctl.h>
static const char *const c_prompt = "Command: ";
static pthread_mutex_t g_stgout_lock = PTHREAD_MUTEX_INITIALIZER;
void log(const char *const msg)
{
pthread_mutex_lock(&g_stgout_lock);
// 3[1A - move cursor one line up
// \r - move cursor to the start of the line
// 3[K - erase from cursor to the end of the line
const char preface[] = "3[1A\r3[K";
write(STDOUT_FILENO, preface, sizeof(preface) - 1);
fprintf(stderr, "%s\n", msg);
fflush(stdout);
const char epilogue[] = "3[K";
write(STDOUT_FILENO, epilogue, sizeof(epilogue) - 1);
fprintf(stdout, "%s", c_prompt);
fflush(stdout);
struct termios tc;
tcgetattr(STDOUT_FILENO, &tc);
const tcflag_t lflag = tc.c_lflag;
// disable echo of control characters
tc.c_lflag &= ~ECHOCTL;
tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
// reprint input buffer
ioctl(STDOUT_FILENO, TIOCSTI, &tc.c_cc[VREPRINT]);
tc.c_lflag = lflag;
tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
pthread_mutex_unlock(&g_stgout_lock);
}
void *thread_proc(void *const arg)
{
const size_t i = (size_t)arg;
char ts[16];
char msg[64];
for (;;)
{
const useconds_t delay = (1.0 + rand() / (double)RAND_MAX) * 1000000;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
usleep(delay);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
time_t t;
time(&t);
ts[strftime(ts, sizeof(ts), "%T", localtime(&t))] = 0;
snprintf(msg, sizeof(msg), "%s - message from #%zu after %lluns",
ts, i, (unsigned long long)delay);
log(msg);
}
}
int main()
{
const size_t N = 4;
pthread_t threads[N];
for (size_t i = N; 0 < i--;)
{
pthread_create(threads + i, 0, thread_proc, (void *)i);
}
char *line;
size_t line_len;
for (;;)
{
pthread_mutex_lock(&g_stgout_lock);
fprintf(stdout, "%s\n", c_prompt);
fflush(stdout);
pthread_mutex_unlock(&g_stgout_lock);
line = fgetln(stdin, &line_len);
if (0 == line)
{
break;
}
if (0 == line_len)
{
continue;
}
line[line_len - 1] = 0;
line[strcspn(line, "\n\r")] = 0;
if (0 == strcmp("exit", line))
{
break;
}
}
for (size_t i = N; 0 < i--;)
{
pthread_cancel(threads[i]);
pthread_join(threads[i], 0);
}
return 0;
}
所用相关文档的链接:
我的测试应用程序在 stderr
中写入日志并使用 stdin
接收来自用户的交互式命令。不用说,任何 stderr
输出都会破坏终端中的用户输入(和命令提示符)。例如这个命令行(_
是光标位置):
Command: reboo_
将变为:
Command: reboo04-23 20:26:12.799 52422 2563 D run@main.cpp:27 started
_
在 log()
调用之后。
为了解决这个问题,我想在终端中使用类似旧版 Quake 控制台的东西,日志在当前输入行上方一行。换句话说,我想得到它:
04-23 20:26:12.799 52422 2563 D run@main.cpp:27 started
Command: reboo_
我可以修改日志记录代码和读取用户输入的代码。希望它适用于 Linux 和 OS X。可以从不同的线程调用 log()
函数。 log()
函数是 stderr
的唯一写入器。
欢迎提出解决该问题(损坏的输入行)的其他建议。我正在寻找无需额外库(如 Curses)即可实施的解决方案。我试图 google 向上,但意识到我需要一种惯用的开场白来理解我到底想要什么。
更新
感谢 Jonathan Leffler 的评论,我意识到我还应该提到 separating stderr
和 stdout
没那么重要。因为我控制了 log()
函数,所以让它写入 stdout
而不是 stderr
不是问题。不过不确定它是否使任务更容易。
更新
精心制作了一些看起来效果不错的东西:
void set_echoctl(const int fd, const int enable)
{
struct termios tc;
tcgetattr(fd, &tc);
tc.c_lflag &= ~ECHOCTL;
if (enable)
{
tc.c_lflag |= ECHOCTL;
}
tcsetattr(fd, TCSANOW, &tc);
}
void log(const char *const msg)
{
// Go to line start
write(1, "\r", 1);
// Erases from the current cursor position to the end of the current line
write(1, "3[K", strlen("3[K"));
fprintf(stderr, "%s\n", msg);
// Move cursor one line up
write(1, "3[1A", strlen("3[1A"));
// Disable echo control characters
set_echoctl(1, 0);
// Ask to reprint input buffer
termios tc;
tcgetattr(1, &tc);
ioctl(1, TIOCSTI, &tc.c_cc[VREPRINT]);
// Enable echo control characters back
set_echoctl(1, 1);
}
但是,它不支持命令提示符("Command: " 在输入行的开头)。但也许我可以为此设置两行 - 一行用于命令提示符,另一行用于输入本身,例如:
Command:
reboo_
这是我做的事情。打开 3 个控制台:
Console #1:(运行程序,输入std::cin)
> ./program > output.txt 2> errors.txt
控制台 #2:(视图 std::cout)
> tail -f output.txt
控制台 #3:(视图 std::cerr)
> tail -f errors.txt
任何程序输入都输入到控制台:#1。
您可以获得一些控制台,例如 Terminator
,允许您将屏幕分成不同的部分:
根据对您可能想使用 readline 库查看的问题的更新:
它将用户输入的底线分开,并将所有内容输出到它上面的线。它还提供了一个可配置的提示符,甚至具有记录输入历史的功能。
下面是一个示例,您可以从中获得灵感来构建 log()
函数:
#include <cstdlib>
#include <memory>
#include <iostream>
#include <algorithm>
#include <readline/readline.h>
#include <readline/history.h>
struct malloc_deleter
{
template <class T>
void operator()(T* p) { std::free(p); }
};
using cstring_uptr = std::unique_ptr<char, malloc_deleter>;
std::string& trim(std::string& s, const char* t = " \t")
{
s.erase(s.find_last_not_of(t) + 1);
s.erase(0, s.find_first_not_of(t));
return s;
}
int main()
{
using_history();
read_history(".history");
std::string shell_prompt = "> ";
cstring_uptr input;
std::string line, prev;
input.reset(readline(shell_prompt.c_str()));
while(input && trim(line = input.get()) != "exit")
{
if(!line.empty())
{
if(line != prev)
{
add_history(line.c_str());
write_history(".history");
prev = line;
}
std::reverse(line.begin(), line.end());
std::cout << line << '\n';
}
input.reset(readline(shell_prompt.c_str()));
}
}
这个简单的例子只是反转你在控制台输入的所有内容。
以下是我想出的最终解决方案。它实际上是一个生成 N 个线程并从每个线程发出日志的工作示例。同时允许交互式用户输入命令。不过,唯一受支持的命令是 "exit"。其他命令将被静默忽略。它有两个小缺陷(就我而言)。
首先一个是命令提示符必须在单独的一行上。像那样:
Command:
reboo_
原因是 VREPRINT
控制字符也发出一个新行。所以我没有找到如何在没有新行的情况下重新打印当前输入缓冲区的方法。
Second 是在打印日志行的同时输入符号时偶尔出现的闪烁。但是尽管闪烁,最终结果是一致的,并且没有观察到线条重叠。也许以后我会想办法避免它,让它变得光滑干净,但已经足够好了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/termios.h>
#include <sys/ioctl.h>
static const char *const c_prompt = "Command: ";
static pthread_mutex_t g_stgout_lock = PTHREAD_MUTEX_INITIALIZER;
void log(const char *const msg)
{
pthread_mutex_lock(&g_stgout_lock);
// 3[1A - move cursor one line up
// \r - move cursor to the start of the line
// 3[K - erase from cursor to the end of the line
const char preface[] = "3[1A\r3[K";
write(STDOUT_FILENO, preface, sizeof(preface) - 1);
fprintf(stderr, "%s\n", msg);
fflush(stdout);
const char epilogue[] = "3[K";
write(STDOUT_FILENO, epilogue, sizeof(epilogue) - 1);
fprintf(stdout, "%s", c_prompt);
fflush(stdout);
struct termios tc;
tcgetattr(STDOUT_FILENO, &tc);
const tcflag_t lflag = tc.c_lflag;
// disable echo of control characters
tc.c_lflag &= ~ECHOCTL;
tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
// reprint input buffer
ioctl(STDOUT_FILENO, TIOCSTI, &tc.c_cc[VREPRINT]);
tc.c_lflag = lflag;
tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
pthread_mutex_unlock(&g_stgout_lock);
}
void *thread_proc(void *const arg)
{
const size_t i = (size_t)arg;
char ts[16];
char msg[64];
for (;;)
{
const useconds_t delay = (1.0 + rand() / (double)RAND_MAX) * 1000000;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
usleep(delay);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
time_t t;
time(&t);
ts[strftime(ts, sizeof(ts), "%T", localtime(&t))] = 0;
snprintf(msg, sizeof(msg), "%s - message from #%zu after %lluns",
ts, i, (unsigned long long)delay);
log(msg);
}
}
int main()
{
const size_t N = 4;
pthread_t threads[N];
for (size_t i = N; 0 < i--;)
{
pthread_create(threads + i, 0, thread_proc, (void *)i);
}
char *line;
size_t line_len;
for (;;)
{
pthread_mutex_lock(&g_stgout_lock);
fprintf(stdout, "%s\n", c_prompt);
fflush(stdout);
pthread_mutex_unlock(&g_stgout_lock);
line = fgetln(stdin, &line_len);
if (0 == line)
{
break;
}
if (0 == line_len)
{
continue;
}
line[line_len - 1] = 0;
line[strcspn(line, "\n\r")] = 0;
if (0 == strcmp("exit", line))
{
break;
}
}
for (size_t i = N; 0 < i--;)
{
pthread_cancel(threads[i]);
pthread_join(threads[i], 0);
}
return 0;
}
所用相关文档的链接: