GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
gets.c
Go to the documentation of this file.
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 /**********************************************************
9  * G_gets (buf)
10  * char *buf buffer to receive data
11  *
12  * does a gets() from stdin. exits upon EOF.
13  * if stdin is a tty (ie, not a pipe or redirected)
14  * then ctrl-z is detected
15  *
16  * returns
17  * 1 read ok
18  * 0 ctrl-z entered. calling routine should re-print a prompt
19  * and call G_gets() again
20  *
21  * note: This is very useful for allowing a program to
22  * reprompt after the program is restarted after
23  * being stopped with a ctrl-Z.
24  *
25  * sample use:
26  * do {
27  * fprintf (stderr, "Enter some input: ") ;
28  * } while ( ! G_gets(buff) ) ;
29  *
30  * If the user suspends the process at this prompt G_gets will return
31  * "0" causing the reprompting.
32  ***********************************************************/
33 
34 static int ctrlz = 0;
35 static void catch_ctrlz(int);
36 static void catch_int(int);
37 
38 
39 int G_gets(char *buf)
40 {
41 #ifdef SIGTSTP
42  RETSIGTYPE(*sigtstp) ();
43  int tty;
44 #endif
45  char p[128];
46  char *eof;
47 
48  ctrlz = 0;
49 #ifdef SIGTSTP
50  if ((tty = isatty(0))) {
51  sigtstp = signal(SIGTSTP, catch_ctrlz);
52  if (sigtstp != (RETSIGTYPE(*)())SIG_DFL)
53  signal(SIGTSTP, sigtstp);
54  }
55 #endif
56  eof = fgets(p, 100, stdin);
57  /* strip the EOL character */
58  if (strlen(p) > 1 && p[strlen(p) - 1] == '\n' && p[strlen(p) - 2] == '\r')
59  p[strlen(p) - 2] = '\0'; /* Handles DOS/Windows "\r\n" */
60  else
61  p[strlen(p) - 1] = '\0'; /* Handles Unix "\n" or old Mac "\r" */
62  /* buf could be any length. Any overflow will occur here. */
63  strcpy(buf, p);
64 
65 #ifdef SIGTSTP
66  if (tty)
67  signal(SIGTSTP, sigtstp);
68 #endif
69  if (eof)
70  return 1;
71  if (ctrlz)
72  return 0;
73 
74  exit(EXIT_SUCCESS);
75 }
76 
77 static void catch_ctrlz(int n)
78 {
79 #ifdef __MINGW32__
80  G_warning("catch_ctrlz: ignored Ctrl-z");
81 #else
82 
83  RETSIGTYPE(*sigint) ();
84 
85  /* having caught ctrlz - effect a ctrl-z using kill */
86  ctrlz = 1;
87  signal(n, SIG_DFL);
88  kill(0, n);
89 
90  /* for berkley systems, ctrlz will not cause eof on read */
91  sigint = signal(SIGINT, catch_int);
92  kill(getpid(), SIGINT);
93  signal(SIGINT, sigint);
94 #endif
95 }
96 
97 static void catch_int(int n)
98 {
99 }
int G_gets(char *buf)
Definition: gets.c:39
char buf[GNAME_MAX+sizeof(G3D_DIRECTORY)+2]
Definition: g3drange.c:62
G_warning("category support for [%s] in mapset [%s] %s", name, mapset, type)
Definition: spawn.c:69
int n
Definition: dataquad.c:291