linux:多线程,一个线程的 block 终端

标签 linux multithreading terminal

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

相关文章:

Linux:用 Lua 表现奇怪的 tput cup

linux - httpd 由于大量 CLOSE_WAIT 而变慢

python - 将模块添加到 pythonpath - 没有任何作用

C++ 异步线程同时运行

c# - 为什么这个 TAP 异步/等待代码比 TPL 版本慢?

windows - 如何使用bat文件在Windows 11终端中启动多个选项卡?

git - 是否可以从终端而不是网站在 github 中创建 pull 请求

c++ - 在订阅时发送环形缓冲区的全部内容,然后发送新数据

windows - 需要自动化从 Linux 到 Windows 的 PPTP 连接

PHP pthreads : Thread dosen't executes methods from other objects async