我想编写一个运行 2 个线程的程序。当主线程忙于工作时,另一个线程充当交互式 cmdline,读取用户输入,然后将某些内容打印到终端。
我的代码现在看起来像这样:
#include <pthread.h>
//Needed for pthread
#ifndef _REENTRANT
#define _REENTRANT
#endif
#include "whatever_u_need.h"
bool g_isDone = false;
void* cmdMain( void* ) {
static char* buf;
buf = (char*)malloc( 257 );
buf[256]=0;
size_t size = 256;
while(!g_isDone) {
printf( "> " );
getline( &buf, &size, stdin );
if( buf[0] == 'q' ) {
g_isDone =true;
break;
}
//echo
puts(buf);
}
free( buf );
pthread_exit(NULL);
}
pthread_t g_cmd_thread;
int main() {
pthread_create( &g_cmd_thread, NULL, cmdMain, NULL );
while(1) {
//non-interactive jobs
}
pthread_cancel( g_cmd_thread );
return 0;
}
问题是,在执行 getline() 时,我按了 ENTER,然后终端向下移动了 2 行。 肯定两个线程都收到了“ENTER 消息”。如何关闭主线程的终端 I/O 但保留其他线程的命令行功能?
我正在使用带有 bash shell 的 Ubuntu。
最佳答案
getline
保留您按回车键时的换行符。然后您puts
该缓冲区并puts
添加一个换行符。因此,终端向下移动了两条线。
来自 man (3) getline:
getline() 从流中读取整行,将包含文本的缓冲区地址存储到 *lineptr 中。缓冲区以 null 结尾并包含换行符(如果找到的话)。
来自 man (3) puts:
puts() writes the string s and a trailing newline to stdout.
关于linux:多线程,一个线程的 block 终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107856/