gets.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <grass/gis.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. /**********************************************************
  8. * G_gets (buf)
  9. * char *buf buffer to receive data
  10. *
  11. * does a gets() from stdin. exits upon EOF.
  12. * if stdin is a tty (ie, not a pipe or redirected)
  13. * then ctrl-z is detected
  14. *
  15. * returns
  16. * 1 read ok
  17. * 0 ctrl-z entered. calling routine should re-print a prompt
  18. * and call G_gets() again
  19. *
  20. * note: This is very useful for allowing a program to
  21. * reprompt after the program is restarted after
  22. * being stopped with a ctrl-Z.
  23. *
  24. * sample use:
  25. * do {
  26. * fprintf (stderr, "Enter some input: ") ;
  27. * } while ( ! G_gets(buff) ) ;
  28. *
  29. * If the user suspends the process at this prompt G_gets will return
  30. * "0" causing the reprompting.
  31. ***********************************************************/
  32. static int ctrlz = 0;
  33. static void catch_ctrlz(int);
  34. static void catch_int(int);
  35. int G_gets(char *buf)
  36. {
  37. #ifdef SIGTSTP
  38. RETSIGTYPE(*sigtstp) ();
  39. int tty;
  40. #endif
  41. char p[128];
  42. char *eof;
  43. ctrlz = 0;
  44. #ifdef SIGTSTP
  45. if ((tty = isatty(0))) {
  46. sigtstp = signal(SIGTSTP, catch_ctrlz);
  47. if (sigtstp != (RETSIGTYPE(*)())SIG_DFL)
  48. signal(SIGTSTP, sigtstp);
  49. }
  50. #endif
  51. eof = fgets(p, 100, stdin);
  52. /* strip the EOL character */
  53. if (strlen(p) > 1 && p[strlen(p) - 1] == '\n' && p[strlen(p) - 2] == '\r')
  54. p[strlen(p) - 2] = '\0'; /* Handles DOS/Windows "\r\n" */
  55. else
  56. p[strlen(p) - 1] = '\0'; /* Handles Unix "\n" or old Mac "\r" */
  57. /* buf could be any length. Any overflow will occur here. */
  58. strcpy(buf, p);
  59. #ifdef SIGTSTP
  60. if (tty)
  61. signal(SIGTSTP, sigtstp);
  62. #endif
  63. if (eof)
  64. return 1;
  65. if (ctrlz)
  66. return 0;
  67. exit(EXIT_SUCCESS);
  68. }
  69. static void catch_ctrlz(int n)
  70. {
  71. #ifdef __MINGW32__
  72. G_warning("catch_ctrlz: ignored Ctrl-z");
  73. #else
  74. RETSIGTYPE(*sigint) ();
  75. /* having caught ctrlz - effect a ctrl-z using kill */
  76. ctrlz = 1;
  77. signal(n, SIG_DFL);
  78. kill(0, n);
  79. /* for berkley systems, ctrlz will not cause eof on read */
  80. sigint = signal(SIGINT, catch_int);
  81. kill(getpid(), SIGINT);
  82. signal(SIGINT, sigint);
  83. #endif
  84. }
  85. static void catch_int(int n)
  86. {
  87. }