-> On Sun, 04 Oct 1998 03:51:10 +0900,
  -> "Niko D. Barli" <[EMAIL PROTECTED]>
  -> in message ::: Re: [id-linux] KEYPRESSED/KBHIT() pada GCC ? ::: wrote,

  >> Baru ketemu nih caranya mengganti kbhit() pake standard C library,
  >> nggak jamin benar 100 %, tapi yang pasti "kelihatannya" jalan.
  >> ini contoh programnya.
  >> 
  >> #include <termios.h>
  >> #include <unistd.h>
  >> #include <stdio.h>
  >> 
  >> /* How to implement if(kbhit()){ do something } */
  >> 
  >> int main(){
  >>   struct termios old_attr, attr;
  >>   int c;
  >> 
  >>   /* save termios old attribute */
  >>   if((tcgetattr)(STDIN_FILENO, &old_attr) < 0){
  >>     exit(-1);
  >>   }
  >>   
  >>   /* set new attribute */
  >>   attr = old_attr;
  >>   attr.c_lflag &= ~(ICANON | ECHO);   /* no buffering and no echoing */
  >>   if((tcsetattr)(STDIN_FILENO,TCSAFLUSH,&attr) < 0){
  >>     exit(-1);
  >>   }
  >> 
  >>   /* get a character */
  >>   c = getchar();
  >>   /* and restore it back before leaving */
  >>   ungetc(c, stdin);
  >> 
  >>   /* restore old attributes */
  >>   if((tcsetattr)(STDIN_FILENO,TCSAFLUSH,&old_attr) < 0){
  >>     exit(-1);
  >>   }
  >> 
  >> 
  >>   /* do something here */
  >> 
  >> 
  >> }

Oops, ada yang kelupaan. Program di atas cuma menunjukkan cara
mematikan fungsi line buffering dari stdin. Untuk meng-emulasi kbhit() 
perlu pake select(). (Mungkin ada cara lebih sederhana ?)

program yang benar :

#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>

/* if(kbhit()){ do something } */

int main(){
  struct timeval polltime;
  fd_set in, inset;

  struct termios old_attr, attr;
  int c;

  /* save termios old attribute */
  if((tcgetattr)(STDIN_FILENO, &old_attr) < 0){
    exit(-1);
  }
  
  /* set new attribute */
  attr = old_attr;
  attr.c_lflag &= ~(ICANON | ECHO);   /* no buffering and no echoing */
  if((tcsetattr)(STDIN_FILENO,TCSAFLUSH,&attr) < 0){
    exit(-1);
  }

  FD_ZERO(&in);
  FD_SET(STDIN_FILENO, &in);

  do{
    polltime.tv_sec  = 0;   /* set time to 0 */
    polltime.tv_usec = 0;   /* to polling    */
    inset = in;

    /* if(!kbhit()) do something else here. Restore
       termios attributes if needed and don't forget to set
       it again before calling select */ 

    printf("a!");

  }
  while(select(1, &inset, NULL, NULL, &polltime) == 0);

  /* restore old attributes */
  if((tcsetattr)(STDIN_FILENO,TCSAFLUSH,&old_attr) < 0){
    exit(-1);
  }


  /* do something here */


}









----------------------------------------------------------------------
Unsubscribe: [EMAIL PROTECTED] 
Archive: http://www.vlsm.org/linux-archive/
Linux CD: [EMAIL PROTECTED]



Kirim email ke