我想编写一个运行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。
答案 0 :(得分:2)
getline
会在您按Enter键时保留换行符。然后,puts
该缓冲区和puts
添加换行符。因此终端向下移动两行。
来自男人(3)getline:
getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.
表示:
puts() writes the string s and a trailing newline to stdout.
答案 1 :(得分:0)
我想我已经犯了这个错误。默认情况下,puts()
会向stdout
添加一个尾随的尾随换行符,这会在上面的代码中产生“双换行符”效果。该bug根本与多线程无关。
猜猜我下次会仔细检查这个手册页。