1 /*
2  * Copyright (c) 2002, 2003, 2004, 2012 by Martin C. Shepherd
3  *
4  * All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, and/or sell copies of the Software, and to permit persons
11  * to whom the Software is furnished to do so, provided that the above
12  * copyright notice(s) and this permission notice appear in all copies of
13  * the Software and that both the above copyright notice(s) and this
14  * permission notice appear in supporting documentation.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
19  * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
20  * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
21  * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
22  * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
23  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
24  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25  *
26  * Except as contained in this notice, the name of a copyright holder
27  * shall not be used in advertising or otherwise to promote the sale, use
28  * or other dealings in this Software without prior written authorization
29  * of the copyright holder.
30  */
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <errno.h>
37 #include <locale.h>
38 #include <setjmp.h>
39 
40 #include <unistd.h>
41 #include <sys/stat.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <signal.h>
45 
46 #ifdef HAVE_SELECT
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
49 #endif
50 #endif
51 
52 #include "libtecla.h"
53 
54 /*
55  * The SignalActions object provides a way to temporarily install
56  * a signal handler to a given set of signals, and later restore all
57  * of the signal handlers that this displaced.
58  */
59 typedef struct {
60   int nsignal;               /* The number of signals on the host OS */
61   sigset_t mask;             /* The set of signals who's signal handlers */
62                              /*  are stored in the following actions[] */
63                              /*  array. */
64   struct sigaction *actions; /* An array of nsignal actions */
65 } SignalActions;
66 
67 static SignalActions *new_SignalActions(void);
68 static SignalActions *del_SignalActions(SignalActions *si);
69 static int displace_signal_handlers(SignalActions *si, sigset_t *mask,
70 				    void (*handler)(int));
71 static int reinstate_signal_handlers(SignalActions *si);
72 
73 /* Return resources, restore the terminal to a usable state and exit */
74 
75 static void cleanup_and_exit(GetLine *gl, SignalActions *si, int status);
76 
77 /* The function which displays the introductory text of the demo */
78 
79 static void show_demo_introduction(GetLine *gl);
80 
81 /* A signal-aware version of select() */
82 
83 static int demo_sigselect(int n, fd_set *readfds, fd_set *writefds,
84 			  fd_set *exceptfds, struct timeval *timeout,
85 			  sigset_t *mask, SignalActions *si);
86 
87 /*
88  * The following variables are accessed from signal handlers.  Note
89  * that these variables don't need to be either volatile or
90  * sig_atomic_t because:
91  *
92  * 1. Outside of signal handlers we only access them when signal
93  *    delivery is blocked, so we know that no signal handlers can
94  *    be accessing them at that time.
95  *
96  * 2. When the signal handlers that set these variables are installed,
97  *    the sa_mask member of the sigaction structure is used to ensure
98  *    that only one instance of these signal handlers can be running
99  *    at a time, so we also know that there can't be simultaneous
100  *    accesses to them by multiple signal handlers.
101  */
102 static GetLine *demo_gl;                /* The line editor object */
103 static sigjmp_buf demo_setjmp_buffer;   /* The sigsetjmp() buffer */
104 static int demo_setjmp_signo = -1;      /* The signal that was caught */
105 
106 /* Signal handlers */
107 
108 static void demo_signal_handler(int signo);
109 static void demo_setjmp_handler(int signo);
110 
111 /*
112  * Set the amount of time that gl_get_line() should wait for I/O before
113  * returning to let the external event loop continue.
114  */
115 #define DEMO_IO_TIMEOUT 100000000 /* ns => 100ms */
116 
117 /* The timeout handler */
118 
119 static GL_TIMEOUT_FN(demo_timeout_fn);
120 
121 /*.......................................................................
122  * This program demonstrates the use of gl_get_line() from an external
123  * event loop. It takes no arguments.
124  */
main(int argc,char * argv[])125 int main(int argc, char *argv[])
126 {
127   int major,minor,micro;      /* The version number of the library */
128   GetLine *gl=NULL;           /* The resource object of gl_get_line() */
129   SignalActions *si=NULL;     /* Temporary storage of displaced signal */
130                               /*  handlers. */
131   sigset_t all_signal_mask;   /* The set of signals known by gl_get_line() */
132 /*
133  * This program requires select().
134  */
135 #if !defined(HAVE_SELECT)
136   fprintf(stderr, "The select() system call isn't available - aborting.\n");
137   exit(1);
138 #else
139 /*
140  * Create the line editor, specifying a maximum line length of 500 bytes,
141  * and 10000 bytes to allocate to storage of historical input lines.
142  */
143   gl = demo_gl = new_GetLine(500, 5000);
144   if(!gl)
145     cleanup_and_exit(gl, si, 1);
146 
147 /*
148  * Allocate an object in which to temporarily record displaced
149  * signal handlers.
150  */
151   si = new_SignalActions();
152   if(!si)
153     cleanup_and_exit(gl, si, 1);
154 /*
155  * If the user has the LC_CTYPE or LC_ALL environment variables set,
156  * enable display of characters corresponding to the specified locale.
157  */
158   (void) setlocale(LC_CTYPE, "");
159 /*
160  * Lookup and display the version number of the library.
161  */
162   libtecla_version(&major, &minor, &micro);
163   printf(
164     "\n Welcome to the server-mode demo program of libtecla version %d.%d.%d\n",
165       major, minor, micro);
166 /*
167  * Display some introductory text, left-justifying it within the current
168  * width of the terminal and enclosing it in a box of asterixes.
169  */
170   show_demo_introduction(gl);
171 /*
172  * Load history.
173  */
174 #ifndef WITHOUT_FILE_SYSTEM
175   (void) gl_load_history(gl, "~/.demo_history", "#");
176 #endif
177 /*
178  * In this demo, rather than having gl_get_line() return immediately
179  * when it would otherwise have to wait for I/O, we register a timeout
180  * callback which causes gl_get_line() to give up waiting after a short
181  * interval.
182  */
183   gl_inactivity_timeout(gl, demo_timeout_fn, NULL, 0, DEMO_IO_TIMEOUT);
184 /*
185  * Install our signal handlers for process termination, suspension and
186  * terminal resize signals. Ignore process continuation signals.
187  */
188   gl_tty_signals(demo_signal_handler, demo_signal_handler, SIG_DFL,
189 		 demo_signal_handler);
190 /*
191  * Get a list of all of the signals that gl_get_line() currently catches.
192  */
193   gl_list_signals(gl, &all_signal_mask);
194 /*
195  * Switch gl_get_line() to non-blocking server mode.
196  */
197   if(gl_io_mode(gl, GL_SERVER_MODE))
198     cleanup_and_exit(gl, si, 1);
199 /*
200  * Instruct gl_get_line() to unblock any signals that it catches
201  * while waiting for input. Note that in non-blocking server mode,
202  * this is only necessary when using gl_inactivity_timeout() to make
203  * gl_get_line() block for a non-zero amount of time.
204  */
205   gl_catch_blocked(gl);
206 /*
207  * Enter the event loop.
208  */
209   while(1) {
210     int nready;        /* The number of file-descriptors that are */
211                        /*  ready for I/O */
212     fd_set rfds;       /* The set of file descriptors to watch for */
213                        /*  readability */
214     fd_set wfds;       /* The set of file descriptors to watch for */
215                        /*  writability */
216 /*
217  * Construct the sets of file descriptors to be watched by select(),
218  * starting from empty sets.
219  */
220     FD_ZERO(&rfds);
221     FD_ZERO(&wfds);
222 /*
223  * To ensure that no signals are received whos handlers might change
224  * the requirements for the contents of the above signal sets, block
225  * all of the signals that we are handling.
226  */
227     sigprocmask(SIG_BLOCK, &all_signal_mask, NULL);
228 /*
229  * Depending on which direction of I/O gl_get_line()s is currently
230  * waiting for, add the terminal file descriptor to either the set
231  * of file descriptors to watch for readability, or those to watch
232  * for writability. Note that at the start of a new line, such as
233  * after an error, or the return of a completed line, we need to
234  * wait for writability, so that a prompt can be written.
235  */
236     switch(gl_pending_io(gl)) {
237     case GLP_READ:
238       FD_SET(STDIN_FILENO, &rfds);
239       break;
240     default:
241       FD_SET(STDIN_FILENO, &wfds);
242       break;
243     };
244 /*
245  * Wait for I/O to become possible on the selected file descriptors.
246  * The following is a signal-aware wrapper around the select() system
247  * call. This wrapper guarantees that if any of the signals marked in
248  * all_signal_mask arrive after the statement above where we blocked
249  * these signals, it will detect this and abort with nready=-1 and
250  * errno=EINTR. If instead, we just unblocked the above signals just
251  * before calling a normal call to select(), there would be a small
252  * window of time between those two statements in which a signal could
253  * arrive without aborting select(). This would be a problem, since
254  * the functions called by our signal handler may change the type
255  * of I/O that gl_get_line() wants us to wait for in select().
256  */
257     nready = demo_sigselect(STDIN_FILENO + 1, &rfds, &wfds, NULL, NULL,
258 			    &all_signal_mask, si);
259 /*
260  * We can now unblock our signals again.
261  */
262     sigprocmask(SIG_UNBLOCK, &all_signal_mask, NULL);
263 /*
264  * Did an I/O error occur?
265  */
266     if(nready < 0 && errno != EINTR)
267       cleanup_and_exit(gl, si, 1);
268 /*
269  * If the terminal file descriptor is now ready for I/O, call
270  * gl_get_line() to continue editing the current input line.
271  */
272     if(FD_ISSET(STDIN_FILENO, &rfds) || FD_ISSET(STDIN_FILENO, &wfds)) {
273 /*
274  * Start or continue editing an input line.
275  */
276       char *line = gl_get_line(gl, "$ ", NULL, 0);
277 /*
278  * Did the user finish entering a new line?
279  */
280       if(line) {
281 /*
282  * Before writing messages to the terminal, start a new line and
283  * switch back to normal terminal I/O.
284  */
285 	gl_normal_io(gl);
286 /*
287  * Display what was entered.
288  */
289 	if(printf("You entered: %s", line) < 0 || fflush(stdout))
290 	  break;
291 /*
292  * Implement a few simple commands.
293  */
294 	if(strcmp(line, "exit\n")==0)
295 	  cleanup_and_exit(gl, si, 0);
296 	else if(strcmp(line, "history\n")==0)
297 	  gl_show_history(gl, stdout, "%N  %T   %H\n", 0, -1);
298 	else if(strcmp(line, "size\n")==0) {
299 	  GlTerminalSize size = gl_terminal_size(gl, 80, 24);
300 	  printf("Terminal size = %d columns x %d lines.\n", size.ncolumn,
301 		 size.nline);
302 	} else if(strcmp(line, "clear\n")==0) {
303 	  if(gl_erase_terminal(gl))
304 	    return 1;
305 	};
306 /*
307  * To resume command-line editing, return the terminal to raw,
308  * non-blocking I/O mode.
309  */
310 	gl_raw_io(gl);
311 /*
312  * If gl_get_line() returned NULL because of an error or end-of-file,
313  * abort the program.
314  */
315       } else if(gl_return_status(gl) == GLR_ERROR ||
316 		gl_return_status(gl) == GLR_EOF) {
317 	cleanup_and_exit(gl, si, 1);
318       };
319     };
320   };
321 #endif
322   return 0;
323 }
324 
325 /*.......................................................................
326  * This function is called to return resources to the system and restore
327  * the terminal to its original state before exiting the process.
328  *
329  * Input:
330  *  gl        GetLine *   The line editor.
331  *  si  SignalActions *   The repository for displaced signal handlers.
332  *  status        int     The exit code of the process.
333  */
cleanup_and_exit(GetLine * gl,SignalActions * si,int status)334 static void cleanup_and_exit(GetLine *gl, SignalActions *si, int status)
335 {
336 /*
337  * Restore the terminal to its original state before exiting the program.
338  */
339   gl_normal_io(gl);
340 /*
341  * Save historical command lines.
342  */
343 #ifndef WITHOUT_FILE_SYSTEM
344   (void) gl_save_history(gl, "~/.demo_history", "#", -1);
345 #endif
346 /*
347  * Clean up.
348  */
349   gl = del_GetLine(gl);
350   si = del_SignalActions(si);
351 /*
352  * Exit the process.
353  */
354   exit(status);
355 }
356 
357 /*.......................................................................
358  * This is a signal-aware wrapper around the select() system call. It
359  * is designed to facilitate reliable signal handling of a given set
360  * of signals, without the race conditions that would usually surround
361  * the use of select(). See the "RELIABLE SIGNAL HANDLING" section of
362  * the gl_get_line(3) man page for further details.
363  *
364  * Provided that the calling function has blocked the specified set of
365  * signals before calling this function, this function guarantees that
366  * select() will be aborted by any signal that arrives between the
367  * time that the caller blocked the specified signals and this
368  * function returns. On return these signals will again be blocked to
369  * prevent any signals that arrive after select() returns, from being
370  * missed by the caller.
371  *
372  * Note that this function is written not to be specific to this
373  * program, and is thus suitable for use in other programs, whether or
374  * not they use gl_get_line().
375  *
376  * Also note that this function depends on the NSIG preprocessor
377  * constant being >= the maximum number of signals available on the
378  * host operating system. Under BSD and SysV, this macro is set
379  * appropriately in signal.h. On other systems, a reasonably large
380  * guess should be substituted. Although nothing terrible will happen
381  * if a value that is too small is chosen, signal numbers that exceed
382  * the specified value of NSIG will be ignored by this function. A
383  * more robust method than depending on nsig would be to use the
384  * POSIX sigismember() function to count valid signals, and use this
385  * to allocate the array of sigaction structures used to preserve
386  *
387  *
388  * Input:
389  *  n                   int    The number of file descriptors to pay
390  *                             attention to at the start of each of the
391  *                             following sets of file descriptors.
392  *  readfds          fd_set *  The set of file descriptors to check for
393  *                             readability, or NULL if not pertinent.
394  *  wwritefds        fd_set *  The set of file descriptors to check for
395  *                             writability, or NULL if not pertinent.
396  *  exceptfds        fd_set *  The set of file descriptors to check for
397  *                             the arrival of urgent data, or NULL if
398  *                             not pertinent.
399  *  timeout  struct timeval *  The maximum time that select() should
400  *                             wait, or NULL to wait forever.
401  *  mask           sigset_t *  The set of signals to catch.
402  *  si       SignalHandlers *  An object in which to preserve temporary
403  *                             copies signal handlers.
404  * Output:
405  *  return              int    > 0  The number of entries in all of the
406  *                                  sets of descriptors that are ready
407  *                                  for I/O.
408  *                               0  Select() timed out.
409  *                              -1  Error (see errno).
410  */
demo_sigselect(int n,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout,sigset_t * mask,SignalActions * si)411 static int demo_sigselect(int n, fd_set *readfds, fd_set *writefds,
412 			  fd_set *exceptfds, struct timeval *timeout,
413 			  sigset_t *mask, SignalActions *si)
414 {
415 /*
416  * The reason that the the following variables are marked as volatile
417  * is to prevent the compiler from placing their values in registers
418  * that might not be saved and restored by sigsetjmp().
419  */
420   volatile sigset_t old_mask;  /* The displaced process signal mask */
421   volatile int status;         /* The return value of select() */
422 /*
423  * Make sure that all of the specified signals are blocked. This is
424  * redundant if the caller has already blocked signals.
425  */
426   if(sigprocmask(SIG_BLOCK, mask, (sigset_t *) &old_mask) < 0)
427     return -1;
428 /*
429  * Record the fact that no signal has been caught yet.
430  */
431   demo_setjmp_signo = -1;
432 /*
433  * Now set up the point where our temporary signal handlers will return
434  * control if a signal is received.
435  */
436   if(sigsetjmp(demo_setjmp_buffer, 1) == 0) {
437 /*
438  * Now install the temporary signal handlers that cause the above
439  * sigsetjmp() to return non-zero when a signal is detected.
440  */
441     if(displace_signal_handlers(si, mask, demo_setjmp_handler)) {
442       reinstate_signal_handlers(si);
443       return 1;
444     };
445 /*
446  * Now that we are ready to catch the signals, unblock them.
447  */
448     sigprocmask(SIG_UNBLOCK, mask, NULL);
449 /*
450  * At last, call select().
451  */
452     status = select(n, readfds, writefds, exceptfds, timeout);
453 /*
454  * Block the specified signals again.
455  */
456     sigprocmask(SIG_BLOCK, mask, NULL);
457 /*
458  * Record the fact that no signal was caught.
459  */
460     demo_setjmp_signo = -1;
461   };
462 /*
463  * We can get to this point in one of two ways. Either no signals were
464  * caught, and the above block ran to completion (with demo_setjmp_signo=-1),
465  * or a signal was caught that caused the above block to be aborted,
466  * in which case demo_setjmp_signo will now equal the number of the signal that
467  * was caught, and sigsetjmp() will have restored the process signal
468  * mask to how it was before it was called (ie. all of the specified
469  * signals blocked).
470  *
471  * First restore the signal handlers to how they were on entry to
472  * this function.
473  */
474   reinstate_signal_handlers(si);
475 /*
476  * Was a signal caught?
477  */
478   if(demo_setjmp_signo > 0) {
479     sigset_t new_mask;
480 /*
481  * Send the signal again, then unblock its delivery, so that the application's
482  * signal handler gets invoked.
483  */
484     raise(demo_setjmp_signo);
485     sigemptyset(&new_mask);
486     sigaddset(&new_mask, demo_setjmp_signo);
487     sigprocmask(SIG_UNBLOCK, &new_mask, NULL);
488 /*
489  * Set the return status to show that a signal was caught.
490  */
491     errno = EINTR;
492     status = -1;
493   };
494 /*
495  * Now restore the process signal mask to how it was on entry to this
496  * function.
497  */
498   sigprocmask(SIG_SETMASK, (sigset_t *) &old_mask, NULL);
499   return status;
500 }
501 
502 /*.......................................................................
503  * This is the main signal handler of this demonstration program. If a
504  * SIGINT is received by the process, it arranges that the next call
505  * to gl_get_line() will abort entry of the current line and start
506  * entering a new one. Otherwise it calls the library function which
507  * handles terminal resize signals and process suspension and process
508  * termination signals. Both of the functions called by this signal
509  * handler are designed to be async-signal safe, provided that the
510  * rules laid out in the gl_io_mode(3) man page are followed.
511  */
demo_signal_handler(int signo)512 static void demo_signal_handler(int signo)
513 {
514   if(signo==SIGINT)
515     gl_abandon_line(demo_gl);
516   else
517     gl_handle_signal(signo, demo_gl, 1);
518 }
519 
520 /*.......................................................................
521  * The following signal handler is installed while select() is being
522  * called from within a block of code protected by sigsetjmp(). It
523  * simply records the signal that was caught in setjmp_signo, then
524  * causes the sigsetjmp() to return non-zero.
525  */
demo_setjmp_handler(int signo)526 static void demo_setjmp_handler(int signo)
527 {
528   demo_setjmp_signo = signo;
529   siglongjmp(demo_setjmp_buffer, 1);
530 }
531 
532 /*.......................................................................
533  * This optional inactivity timeout function is used in this
534  * demonstration to cause gl_get_line() to wait for a small amount of
535  * time for I/O, before returning and allowing the event loop to
536  * continue. This isn't needed if you want gl_get_line() to return
537  * immediately, rather than blocking.
538  */
GL_TIMEOUT_FN(demo_timeout_fn)539 static GL_TIMEOUT_FN(demo_timeout_fn)
540 {
541   return GLTO_CONTINUE;
542 }
543 
544 /*.......................................................................
545  * Display introductory text to the user, formatted according to the
546  * current terminal width and enclosed in a box of asterixes.
547  *
548  * Input:
549  *  gl      GetLine *   The resource object of gl_get_line().
550  */
show_demo_introduction(GetLine * gl)551 static void show_demo_introduction(GetLine *gl)
552 {
553   int start;     /* The column in which gl_display_text() left the cursor */
554   int i;
555 /*
556  * Break the indtroductory text into an array of strings, so as to
557  * avoid overflowing any compiler string limits.
558  */
559   const char *doc[] = {
560     "To the user this program appears to act identically to the main ",
561     "demo program. However whereas the code underlying the main demo ",
562     "program uses gl_get_line() in its default configuration, where each ",
563     "call blocks the caller until the user has entered a complete input ",
564     "line, demo3 uses gl_get_line() in its non-blocking server mode, ",
565     "where it must be called repeatedly from an external ",
566     "event loop to incrementally accept entry of the input ",
567     "line, as and when terminal I/O becomes possible. The well commented ",
568     "source code of demo3, which can be found in demo3.c, thus provides ",
569     "a working example of how to use gl_get_line() in a manner that ",
570     "doesn't block the caller. Documentation of this mode can be found ",
571     "in the gl_io_mode(3) man page.\n"
572   };
573 /*
574  * Form the top line of the documentation box by filling the area of
575  * the line between a " *" prefix and a "* " suffix with asterixes.
576  */
577   printf("\n");
578   gl_display_text(gl, 0, " *", "* ", '*', 80, 0, "\n");
579 /*
580  * Justify the documentation text within margins of asterixes.
581  */
582   for(start=0,i=0; i<sizeof(doc)/sizeof(doc[0]) && start >= 0; i++)
583     start = gl_display_text(gl, 0, " * ", " * ", ' ', 80, start,doc[i]);
584 /*
585  * Draw the bottom line of the documentation box.
586  */
587   gl_display_text(gl, 0, " *", "* ", '*', 80, 0, "\n");
588   printf("\n");
589 }
590 
591 
592 /*.......................................................................
593  * This is a constructor function for an object who's role is to allow
594  * a signal handler to be assigned to potentially all available signals,
595  * while preserving a copy of the original signal handlers, for later
596  * restration.
597  *
598  * Output:
599  *  return  SignalActions *  The new object, or NULL on error.
600  */
new_SignalActions(void)601 static SignalActions *new_SignalActions(void)
602 {
603   SignalActions *si;  /* The object to be returned */
604 /*
605  * Allocate the container.
606  */
607   si = malloc(sizeof(SignalActions));
608   if(!si) {
609     fprintf(stderr, "new_SignalActions: Insufficient memory.\n");
610     return NULL;
611   };
612 /*
613  * Before attempting any operation that might fail, initialize the
614  * container at least up to the point at which it can safely be passed
615  * to del_SignalActions().
616  */
617   si->nsignal = 0;
618   sigemptyset(&si->mask);
619   si->actions = NULL;
620 /*
621  * Count the number of signals that are available of the host
622  * platform. Note that si->mask has no members set, and that
623  * sigismember() is defined to return -1 if the signal number
624  * isn't valid.
625  */
626   for(si->nsignal=1; sigismember(&si->mask, si->nsignal) == 0; si->nsignal++)
627     ;
628 /*
629  * Allocate the array of sigaction structures to use to keep a record
630  * of displaced signal handlers.
631  */
632   si->actions = (struct sigaction *) malloc(sizeof(*si->actions) * si->nsignal);
633   if(!si->actions) {
634     fprintf(stderr, "Insufficient memory for %d sigaction structures.\n",
635 	    si->nsignal);
636     return del_SignalActions(si);
637   };
638   return si;
639 }
640 
641 /*.......................................................................
642  * Delete a SignalActions object.
643  *
644  * Input:
645  *  si     SignalActions *  The object to be deleted.
646  * Output:
647  *  return SignalActions *  The deleted object (always NULL).
648  */
del_SignalActions(SignalActions * si)649 static SignalActions *del_SignalActions(SignalActions *si)
650 {
651   if(si) {
652     if(si->actions)
653       free(si->actions);
654     free(si);
655   };
656   return NULL;
657 }
658 
659 /*.......................................................................
660  * Replace the signal handlers of all of the signals in 'mask' with
661  * the signal handler 'handler'.
662  *
663  * Input:
664  *  si       SignalActions *     The object in which to record the displaced
665  *                               signal handlers.
666  *  mask          sigset_t *     The set of signals who's signal handlers
667  *                               should be displaced.
668  *  handler void (*handler)(int) The new signal handler to assign to each
669  *                               of the signals marked in 'mask'.
670  * Output:
671  *  return             int       0 - OK.
672  *                               1 - Error.
673  */
displace_signal_handlers(SignalActions * si,sigset_t * mask,void (* handler)(int))674 static int displace_signal_handlers(SignalActions *si, sigset_t *mask,
675 				    void (*handler)(int))
676 {
677   int signo;                /* A signal number */
678   struct sigaction action;  /* The new signal handler */
679 /*
680  * Mark the fact that so far we haven't displaced any signal handlers.
681  */
682   sigemptyset(&si->mask);
683 /*
684  * Set up the description of the new signal handler. Note that
685  * we make sa_mask=mask. This ensures that only one instance of the
686  * signal handler will ever be running at one time.
687  */
688   action.sa_handler = handler;
689   memcpy(&action.sa_mask, mask, sizeof(*mask));
690   action.sa_flags = 0;
691 /*
692  * Check each of the available signals to see if it is specified in 'mask'.
693  * If so, install the new signal handler, record the displaced one in
694  * the corresponding element of si->actions[], and make a record in
695  * si->mask that this signal handler has been displaced.
696  */
697   for(signo=1; signo < si->nsignal; signo++) {
698     if(sigismember(mask, signo)) {
699       if(sigaction(signo, &action, &si->actions[signo]) < 0) {
700 	fprintf(stderr, "sigaction error (%s)\n", strerror(errno));
701 	return 1;
702       };
703       sigaddset(&si->mask, signo);
704     };
705   };
706   return 0;
707 }
708 
709 /*.......................................................................
710  * Reinstate any signal handlers displaced by displace_signal_handlers().
711  *
712  * Input:
713  *  sig   SignalActions *  The object containing the displaced signal
714  *                         handlers.
715  * Output:
716  *  return          int    0 - OK.
717  *                         1 - Error.
718  */
reinstate_signal_handlers(SignalActions * si)719 static int reinstate_signal_handlers(SignalActions *si)
720 {
721   int signo;                /* A signal number */
722 /*
723  * Check each of the available signals to see if it is specified in
724  * si->mask. If so, reinstate the displaced recorded in the
725  * corresponding element of si->actions[], and make a record in
726  * si->mask that this signal handler has been reinstated.
727  */
728   for(signo=1; signo < si->nsignal; signo++) {
729     if(sigismember(&si->mask, signo)) {
730       if(sigaction(signo, &si->actions[signo], NULL) < 0) {
731 	fprintf(stderr, "sigaction error (%s)\n", strerror(errno));
732 	return 1;
733       };
734       sigdelset(&si->mask, signo);
735     };
736   };
737   return 0;
738 }
739