我正在处理部分操作系统分配,其中涉及使用ncurses.h
,我遇到了一个奇怪的问题。下面的代码执行正常,但是每次在输出中键入字符a
时,终端都会标记。
我使用clang -Wall -lpthread -lncurses test.c
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void move_character(char character);
void initialize_screen();
pthread_t attendees[50];
pthread_mutex_t lock;
static int curses_initialized = FALSE;
void* func(void* arg) {
return NULL;
}
void initialize_screen() {
assert(!curses_initialized);
initscr();
start_color();
curses_initialized = TRUE;
}
int main(int argc, char** argv) {
printf("HRE");
char ch;
pthread_create(&attendees[0], NULL, func, NULL);
pthread_join(attendees[0], NULL);
initialize_screen();
while ((ch = getch()) != '`') {
if (ch >= 'a' && ch <= 'z') {
move_character(ch);
}
}
}
void move_character(char character) {
// Multi-thread here
// Check if thread is not already made (came from the file)
if(attendees[character - 'a'] != NULL) {
pthread_mutex_lock(&lock);
printf("FERN\n");
fflush(stdout);
pthread_mutex_unlock(&lock);
}
}
输出如下:
aFERN
aFERN
aFERN
aFERN
aFERN
aFERN
aFERN
bbccaFERN
aFERN
答案 0 :(得分:1)
您最好在诅咒中使用printw()
代替printf()
。
void move_character(char character) {
// Multi-thread here
// Check if thread is not already made (came from the file)
if(attendees[character - 'a'] != 0) {
pthread_mutex_lock(&lock);
printw("FERN\n");
// fflush(stdout);
pthread_mutex_unlock(&lock);
}
}
,输出正常:
aFERN
aFERN
aFERN
aFERN