gets.c

Go to the documentation of this file.
00001 #include <grass/gis.h>
00002 #include <unistd.h>
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 #include <string.h>
00006 #include <signal.h>
00007 /**********************************************************
00008  * G_gets (buf)
00009  *    char *buf      buffer to receive data
00010  *
00011  *  does a gets() from stdin. exits upon EOF.
00012  *  if stdin is a tty (ie, not a pipe or redirected)
00013  *  then ctrl-z is detected
00014  *
00015  * returns
00016  *  1 read ok
00017  *  0 ctrl-z entered. calling routine should re-print a prompt
00018  *    and call G_gets() again
00019  *
00020  * note: This is very useful for allowing a program to 
00021  *       reprompt after the program is restarted after
00022  *       being stopped with a ctrl-Z.
00023  *
00024  * sample use:
00025  *   do {
00026  *      fprintf (stderr, "Enter some input:  ") ;
00027  *   } while ( ! G_gets(buff) )  ;
00028  *
00029  *   If the user suspends the process at this prompt G_gets will return
00030  *   "0" causing the reprompting.
00031  ***********************************************************/
00032 
00033 static int ctrlz = 0;
00034 static void catch_ctrlz (int);
00035 static void catch_int (int);
00036 
00037 
00038 int G_gets (char *buf)
00039   {
00040         void (*sigtstp)();
00041         int tty;
00042         char p[128];
00043         char *eof;
00044   
00045         ctrlz = 0;
00046 #ifdef SIGTSTP
00047         if ((tty = isatty(0)))
00048         {
00049                 sigtstp = signal (SIGTSTP, catch_ctrlz);
00050                 if (sigtstp != (void (*)()) SIG_DFL)
00051                     signal (SIGTSTP, sigtstp);
00052         }
00053 #endif
00054       eof = fgets(p,100,stdin);
00055       /* strip the EOL character      */
00056       p[strlen(p)-1]='\0';
00057       /*      buf could be any length.  Any overflow will occur here. */
00058       strcpy(buf,p);
00059 
00060 #ifdef SIGTSTP
00061         if (tty)
00062                 signal (SIGTSTP, sigtstp);
00063 #endif
00064         if (eof)
00065                 return 1;
00066         if (ctrlz)
00067                 return 0;
00068         exit(1);
00069   }
00070   
00071 static void catch_ctrlz (int n)
00072   {
00073 #ifdef __MINGW32__
00074       G_warning ( "catch_ctrlz: ignored Ctrl-z" );
00075 #else
00076       
00077         void (*sigint)();
00078   
00079   /* having caught ctrlz - effect a ctrl-z using kill */
00080         ctrlz = 1;
00081         signal (n, SIG_DFL);
00082         kill (0, n);
00083 
00084 /* for berkley systems, ctrlz will not cause eof on read */
00085         sigint = signal (SIGINT, catch_int);
00086         kill (getpid(), SIGINT);
00087         signal (SIGINT, sigint);
00088 #endif
00089 }
00090 
00091 static void catch_int (int n)
00092 {
00093 }

Generated on Fri Nov 21 11:02:18 2008 for GRASS by  doxygen 1.5.1