我想编写一个运行2个线程的程序。当主线程忙于完成工作时,另一个线程充当交互式cmdline,读取用户输入,然后打印某些内容到终端。linux:多线程,一个线程的块终端
我的代码看起来是这样的现:
#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(),I敲击回车键,则移动终端2行下降。 当然,两个线程都已收到“ENTER消息”。如何关闭主线程的终端I/O,但保持其他线程的命令行功能?
我使用Ubuntu和bash shell。
@David Schwartz我做了一个修改。 – Kh40tiK