1. 程式人生 > >關閉回顯,並且中斷訊號關閉,輸入密碼

關閉回顯,並且中斷訊號關閉,輸入密碼

sigprocmask只能用在單執行緒程序
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <termios.h>
  4. #include <error.h>
  5. #include "myerror.h"
  6. #include "file.h"
  7. #include <signal.h>
  8. #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)
  9. int DelayInt(sigset_t * sigold){
  10.     sigset_t signew;
  11. if( (sigemptyset(&signew) == -1) ||
  12.         (sigaddset(&signew, SIGINT) == -1) ||
  13.         (sigaddset(&signew,SIGQUIT) == -1) ||
  14.         (sigaddset(&signew,SIGTSTP) == -1) ){
  15. return -1;
  16.     }
  17. if( sigprocmask(SIG_BLOCK,&signew,sigold) == -1){
  18. return -1;
  19.     }
  20. return 0;
  21. }
  22. int ReleaseDelay(sigset_t * sigold){
  23. if(sigprocmask(SIG_SETMASK,sigold,NULL) == -1)
  24. return -1;
  25. return 0;
  26. }
  27. int SetMode(int fd,int option){
  28. struct termios term;
  29. if(tcgetattr(fd,&term) == -1){
  30. return -1;
  31.     }
  32. if(option)
  33.         term.c_lflag |= ECHOFLAGS;
  34. else
  35.         term.c_lflag &= ~ECHOFLAGS;
  36. if(tcsetattr(fd,TCSAFLUSH,&term) == -1){
  37. return -1;
  38.     }
  39. return 0;
  40. }
  41. int GetPassword(char * passwd,
    int size){
  42. int retval;
  43.     retval = ReadLine(STDIN_FILENO,passwd,size);
  44. if(retval < 0)
  45. return -1;
  46. return retval;
  47. }
  48. 測試執行
  49. #include <stdio.h>
  50. #include <fcntl.h>
  51. #include <errno.h>
  52. #include <stdlib.h>
  53. #include <unistd.h>
  54. #include <sys/types.h>
  55. #include <sys/stat.h>
  56. #include <signal.h>
  57. #include "mystring.h"
  58. #include "file.h"
  59. #include "tools.h"
  60. #include "myerror.h"
  61. #include "restart.h"
  62. #include "passwd.h"
  63. int main(int argc,char *argv[]){
  64. char passwd[20] = {0};
  65. int turn = 1;
  66. int retval;
  67.     sigset_t sigold;    
  68. if(DelayInt(&sigold) == -1){
  69.         fprintf(stderr,"delayint error!/n");
  70. return -1;
  71.     }
  72. while(turn){
  73.         printf("/nPlease Input your password:");
  74.         fflush(stdout);
  75.         SetMode(STDIN_FILENO,0);
  76.         retval = GetPassword(passwd,sizeof(passwd));
  77. if(retval < 0)
  78.             turn = 1;
  79. else
  80.             turn = 0;
  81.         SetMode(STDIN_FILENO,1);
  82.     }
  83. while(ReleaseDelay(&sigold) == -1)
  84.         ;
  85.     printf("/nYour password is %s/n",passwd);
  86. return 0;
  87. }