PDA

View Full Version : nonblocking STDIN


gurutech
19-04-2007, 19:34
ciao,
sto cercando di leggere un carattere dallo STDIN in C.
il carattere che leggo deve essere accettato senza dare invio, e il programma deve proseguire se non c'è alcun input.
qui (http://developer.apple.com/documentation/OpenSource/Conceptual/ShellScripting/AdvancedTechniques/chapter_9_section_3.html) ho trovato una soluzione, ma ho letto spulciando su internet che forse mettere STDIN nonblocking non è una buona soluzione: perchè? alternative ?
tnx

gurutech
19-04-2007, 20:06
così può andare?
tenete presente che nel frattempo devo leggere e scrivere su una seriale, e la pressione dei tasti NON DEVE alterare ciò che leggo/scrivo sulla RS232

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>

int main(int argc, char *argv[])
{
int ch,i;
struct termios options;

tcgetattr(STDIN_FILENO,&options);
options.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&options);

int flags = fcntl(STDIN_FILENO, F_GETFL);
if (flags == -1) return -1; // error
fcntl(STDIN_FILENO, F_SETFL, (flags | O_NONBLOCK) & ~ICANON);
for (i=0;i<500;i++) {
ch = fgetc(stdin);
if (ch!=-1) printf("%c * %02x\n",ch,ch);
usleep(100);
}

tcgetattr(STDIN_FILENO,&options);
options.c_lflag |= (ICANON | ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&options);

return 0;
}

gurutech
22-04-2007, 01:57
ho risolto più elegantemente passando a ncurses (che non avevo mai usato prima!)