Reputation: 2336
I want to write a program running 2 threads. While main thread busy doing its job, the other thread act as an interactive cmdline, reads user input, then print something to terminal.
My code looks like this now:
#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;
}
The problem is, when executing getline(), I hit ENTER, then the terminal moves 2 lines down. Definitely both threads have recieved the "ENTER message". How can I turn off the terminal I/O for the main thread but keeping the other thread's command-line functionality?
I'm using Ubuntu with bash shell.
Upvotes: 0
Views: 400
Reputation: 27552
getline
retains the newline from when you hit enter. You then puts
that buffer and puts
adds a newline. Thus the terminal moves down two lines.
from man (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.
from man (3) puts:
puts() writes the string s and a trailing newline to stdout.
Upvotes: 2
Reputation: 2336
I think I've got the bug. By default, puts()
adds a trailing trailing newline to the stdout
, which produces "double newline" effect in the above code. The bug has nothing to do with multithreading at all.
Guess I'll double-check the man page next time.
Upvotes: 0