0

2 つのスレッドを実行するプログラムを作成したいと考えています。メインスレッドが仕事をしている間、他のスレッドはインタラクティブなコマンドラインとして機能し、ユーザー入力を読み取り、端末に何かを出力します。

私のコードは次のようになります。

#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 シェルで Ubuntu を使用しています。

4

2 に答える 2

2

getlineEnter キーを押したときの改行を保持します。次に、putsそのバッファをputs作成して改行を追加します。したがって、端末は 2 行下に移動します。

男から (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.
于 2013-10-01T04:52:27.787 に答える
0

私はバグを持っていると思います。デフォルトでputs()は、 は末尾に末尾の改行を追加しますstdout。これにより、上記のコードで「二重改行」効果が生成されます。このバグは、マルチスレッドとはまったく関係ありません。

次回はマニュアルページを再確認しようと思います。

于 2013-10-01T04:57:31.797 に答える