Bash-4.3 distribution sources and documentation
[platform/upstream/bash.git] / lib / readline / examples / rl-callbacktest.c
1 /* Standard include files. stdio.h is required. */
2 #include <stdlib.h>
3 #include <unistd.h>
4
5 /* Used for select(2) */
6 #include <sys/types.h>
7 #include <sys/select.h>
8
9 #include <stdio.h>
10
11 /* Standard readline include files. */
12 #include <readline/readline.h>
13 #include <readline/history.h>
14
15 static void cb_linehandler (char *);
16
17 int running;
18 const char *prompt = "rltest$ ";
19
20 /* Callback function called for each line when accept-line executed, EOF
21    seen, or EOF character read.  This sets a flag and returns; it could
22    also call exit(3). */
23 static void
24 cb_linehandler (char *line)
25 {
26   /* Can use ^D (stty eof) or `exit' to exit. */
27   if (line == NULL || strcmp (line, "exit") == 0)
28     {
29       if (line == 0)
30         printf ("\n");
31       printf ("exit\n");
32       /* This function needs to be called to reset the terminal settings,
33          and calling it from the line handler keeps one extra prompt from
34          being displayed. */
35       rl_callback_handler_remove ();
36
37       running = 0;
38     }
39   else
40     {
41       if (*line)
42         add_history (line);
43       printf ("input line: %s\n", line);
44       free (line);
45     }
46 }
47
48 int
49 main (int c, char **v)
50 {
51   fd_set fds;
52   int r;
53
54   /* Install the line handler. */
55   rl_callback_handler_install (prompt, cb_linehandler);
56
57   /* Enter a simple event loop.  This waits until something is available
58      to read on readline's input stream (defaults to standard input) and
59      calls the builtin character read callback to read it.  It does not
60      have to modify the user's terminal settings. */
61   running = 1;
62   while (running)
63     {
64       FD_ZERO (&fds);
65       FD_SET (fileno (rl_instream), &fds);    
66
67       r = select (FD_SETSIZE, &fds, NULL, NULL, NULL);
68       if (r < 0)
69         {
70           perror ("rltest: select");
71           rl_callback_handler_remove ();
72           break;
73         }
74
75       if (FD_ISSET (fileno (rl_instream), &fds))
76         rl_callback_read_char ();
77     }
78
79   printf ("rltest: Event loop has exited\n");
80   return 0;
81 }