2013-10-01 30 views
0

我想编写一个运行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。

+0

@David Schwartz我做了一个修改。 – Kh40tiK

回答

2

getline从您输入时保留换行符。然后您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.

从人(3)提出:

puts() writes the string s and a trailing newline to stdout. 
+1

刚刚检查了手册页,就是这样。我很愚蠢。 – Kh40tiK

0

我想我已经得到了错误。默认情况下,puts()stdout中添加了尾随的换行符,在上面的代码中会产生“双换行”效果。这个bug与多线程无关。

猜猜我下次会仔细检查手册页。