un altro esempio:
[anche uguale, ma senza malloc (e setts e flags non dichiarati come puntatori)]:
codice:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <termios.h>
#include <pthread.h>
static unsigned char c;
void *exit_thr(void *p);
int main(void)
{
int x, p;
pthread_t get_input;
struct termios *setts; /*"$ man termios" per maggiori dettagli.*/
tcflag_t *flags;
x = 0;
flags = malloc(sizeof (tcflag_t)); /*...*/
setts = malloc(sizeof (struct termios));
assert((flags != NULL)
&& (setts != NULL));
p = pthread_create(&get_input, NULL, exit_thr, NULL);
tcgetattr(STDIN_FILENO, setts);
*flags = setts->c_lflag;
setts->c_lflag &= (~ICANON & ~ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, setts);
for (; ;)
{
if (c == 'x')
break;
printf("%d\n", x);
++x;
}
setts->c_lflag = *flags;
tcsetattr(STDIN_FILENO, TCSANOW, setts);
free(flags);
free(setts);
return 0;
}
void *exit_thr(void *p)
{
while(!((c = getchar()) == 'x'))
;
c = 'x'; /*Non mi fido della getchar().*/
pthread_exit(NULL);
return 0;
}
lo compili con: gcc -ansi -pedantic -Wall -Werror -lpthread <file>
...non capisco il perchè, ma ogni tanto non termina appena
viene premuto 'x'
comunque la maggior parte (credo...) dei programmi
utilizza la libreria 'curses' (o la 'ncurses') per fare certe cose.