gl_io_mode(3)
π gl_io_mode β bestie edition
okay so this is the gl_io_mode(3) page from the Library Functions Manual, and it's literally the manual for how to use gl_get_line() from an external event loop. Buckle up, we're doing non-blocking I/O and it's a whole thing π
β¨ NAME β¨
gl_io_mode, gl_raw_io, gl_normal_io, gl_tty_signals, gl_abandon_line, gl_handle_signal, gl_pending_io β how to use gl_get_line() from an external event loop. no cap, that's the whole vibe.
πΈ SYNOPSIS πΈ
#include <libtecla.h>
int gl_io_mode(GetLine *gl, GlIOMode mode);
int gl_raw_io(GetLine *gl);
int gl_normal_io(GetLine *gl);
int gl_tty_signals(void (*term_handler)(int),
void (*susp_handler)(int),
void (*cont_handler)(int),
void (*size_handler)(int));
void gl_abandon_line(GetLine *gl);
void gl_handle_signal(int signo, GetLine *gl, int ngl);
GlPendingIO gl_pending_io(GetLine *gl);
π DESCRIPTION π
so gl_get_line() β which has its own whole separate page, gl_get_line(3), go read it bestie β supports two different I/O modes. you pick which one you want by calling gl_io_mode().
int gl_io_mode(GetLine *gl, GlIOMode mode);
the mode argument says which new I/O mode you want, and it has to be one of these two, no third option, periodt:
GL_NORMAL_MODEβ select the normal blocking-I/O mode. in this modegl_get_line()does not return until either an error occurs or the user finishes entering a new line. this mode is the whole focus of thegl_get_line(3)man page.GL_SERVER_MODEβ select non-blocking server I/O mode. in this mode, since non-blocking terminal I/O is used, entering each new input line typically takes many calls togl_get_line()from an external I/O-driven event loop. this mode is the whole focus of this man page.
newly created GetLine objects start out in normal I/O mode, so if you wanna switch to non-blocking server mode you gotta make an initial call to gl_io_mode(). one call. that's it. π«Ά
π¦ SERVER I/O MODE π¦
in non-blocking server I/O mode, your application is required to have an event loop that calls gl_get_line() whenever the terminal file descriptor can do the type of I/O that gl_get_line() is waiting for. and how do you know which type of I/O it's waiting for? you call gl_pending_io(), bestie.
GlPendingIO gl_pending_io(GetLine *gl);
the return value is one of these two enumerated values:
GLP_READβgl_get_line()is waiting to write a character to the terminal.GLP_WRITEβgl_get_line()is waiting to read a character from the keyboard.
if your app is using either the select() or poll() system calls to watch for I/O on a group of file descriptors, then you should call gl_pending_io() before each call to those functions, so you can see which direction of I/O you need to tell them to watch for, and set up their arguments accordingly. in the case of the select() system call, that means using the FD_SET() macro to add the terminal file descriptor either to the set of file descriptors watched for readability, or the set watched for writability. slay.
as in normal I/O mode, the return value of gl_get_line() is either a pointer to a completed input line, or NULL. but β and this is the plot twist β whereas in normal I/O mode a NULL return always means an error happened, in non-blocking server mode NULL is also returned when gl_get_line() can't read or write to the terminal without blocking. so in non-blocking server mode, to figure out whether a NULL return means "error" or "just vibing, waiting for I/O", you have to call the gl_return_status() function. if that function returns the enumerated value GLR_BLOCKED, as documented over in the gl_get_line(3) man page, that means gl_get_line() is waiting for I/O and no error has occurred. icon behaviour honestly.
when gl_get_line() returns NULL and gl_return_status() says it's because of blocked terminal I/O, your app should call gl_get_line() again when the type of I/O reported by gl_pending_io() becomes possible. on those calls, the prompt, start_line and start_pos arguments of gl_get_line() will be ignored. and if you need to change the prompt of the line currently being edited, you can call the gl_replace_prompt() function (documented in the gl_get_line(3) man page) between calls to gl_get_line(). π
π GIVING UP THE TERMINAL π
here's the complication that's unique to non-blocking server mode: it requires that the terminal be left in raw mode between calls to gl_get_line(). if that weren't the case, the external event loop couldn't detect individual key-presses, and the basic line editing done by the terminal driver would clash with the editing gl_get_line() provides. so what does that mean for you? it means any time the terminal needs to be used for something other than entering a new input line with gl_get_line(), it needs to be restored to a usable state. in particular, whenever the process is suspended or terminated, the terminal must be returned to a normal state.
bestie. if this isn't done, then depending on the characteristics of the shell used to invoke the program, the user may end up with a hung terminal. π not cute.
to that end, the gl_normal_io() function exists β it switches the terminal back to the state it was in when raw mode was last established.
int gl_normal_io(GetLine *gl);
what it does: first it flushes any pending output to the terminal, then it moves the cursor to the start of the terminal line that follows the end of the incompletely entered input line. at that point it's safe to suspend or terminate the process, and it's safe for the application to read and write to the terminal. and to resume entry of the input line, your application should call the gl_raw_io() function.
int gl_raw_io(GetLine *gl);
this one starts a new line, redisplays the partially completed input line (if any), restores the cursor position within that line to where it was when gl_normal_io() was called, then switches back to raw, non-blocking terminal mode, ready to continue entry of the input line when gl_get_line() is next called. π
heads up: in non-blocking server mode, ifgl_get_line()is called after a call togl_normal_io()without an intervening call togl_raw_io(), thengl_get_line()will callgl_raw_mode()itself, and the terminal will remain in this mode whengl_get_line()returns. noted. π«‘
π SIGNAL HANDLING π
so in the previous section we said that in non-blocking server mode, the terminal has to be restored to a sane state whenever a signal arrives that either suspends or terminates the process. in normal I/O mode, gl_get_line() does that for you. but in non-blocking server mode, since the terminal is left in raw mode between calls to gl_get_line(), this signal handling has to be done by the application. π and since there are so many signals that can suspend or terminate a process, plus other signals that matter to gl_get_line() β like the SIGWINCH signal, which tells it when the terminal size changed β the gl_tty_signals() function exists to install signal handlers for all the pertinent signals.
int gl_tty_signals(void (*term_handler)(int),
void (*susp_handler)(int),
void (*cont_handler)(int),
void (*size_handler)(int));
what it does is use gl_get_line()'s internal list of signals to assign your specified signal handlers to groups of signals. the arguments go like this:
term_handlerβ the signal handler used to trap signals that by default terminate any process that receives them (eg.SIGINTorSIGTERM).susp_handlerβ the signal handler used to trap signals that by default suspend any process that receives them (eg.SIGTSTPorSIGTTOU).cont_handlerβ the signal handler used to trap signals that are usually sent when a process resumes after being suspended (usuallySIGCONT). β οΈ beware that there is nothing stopping a user from sending one of these signals at other times.size_handlerβ this signal handler is used to trap signals that are sent to processes when their controlling terminals are resized by the user (eg.SIGWINCH).
these arguments can all be the same if you want, no judgement, and you can specify SIG_IGN (ignore this signal) or SIG_DFL (use the system-provided default signal handler) instead of a function where pertinent. in particular, it's rarely useful to trap SIGCONT, so the cont_handler argument will usually be SIG_DFL or SIG_IGN. π
gl_tty_signals() uses the POSIX sigaction() function to install these signal handlers, and it's careful to use the sa_mask member of each sigaction structure to make sure only one of these signals is ever delivered at a time. that guards against different instances of these signal handlers all trying to write to common global data at the same time β stuff like a shared sigsetjmp() buffer or a signal-received flag. mutual exclusion but make it signals. β¨
the signal handlers that get installed by this function should call gl_handle_signal().
void gl_handle_signal(int signo, GetLine *gl, int ngl);
the signo argument tells this function which signal it's being asked to respond to, and the gl argument should be a pointer to the first element of an array of ngl GetLine objects. if your application only has one of these objects, just pass its pointer as the gl argument and specify ngl as 1. easy.
depending on which signal is being handled, this function does different things:
π₯ Terminal resize signals (SIGWINCH)
if the signal indicates the terminal was resized, then it arranges for the next call to gl_get_line() to ask the terminal for its new size and redraw the input line accordingly. and so that gl_get_line() gets called as soon as possible to do that, gl_handle_signal() also arranges that the next call to gl_pending_io() will return GLP_WRITE. so if your application waits for I/O in select() or poll(), then your application needs to make sure these functions will be reliably aborted when a signal is caught and handled by the application. more on this below. π
Process termination signals.
So when the signal that got caught is one of those that would normally just yeet the whole process into the void by default, gl_handle_signal() does this little routine:
- First it blocks the delivery of all signals that can be blocked (ie.
SIGKILLandSIGSTOPcan't be blocked, they're built different π) - Next it calls
gl_normal_io()for each of thenglGetLine objects. Note that this does nothing to any of the GetLine objects that aren't currently in raw mode. - Next it sets the signal handler of the signal to its default, process-termination disposition.
- Next it re-sends the process the signal that was caught.
- Finally it unblocks delivery of this signal, which results in the process being terminated.
Process suspension signals.
If the default disposition of the signal is to suspend the process instead, it's the same steps as for process termination signals, except that when the process is later resumed, gl_handle_signal() picks right back up and does these:
- It re-blocks delivery of the signal.
- It reinstates the signal handler of the signal to the one that was displaced when its default disposition was substituted.
- For any of the GetLine objects that were in raw mode when
gl_handle_signal()was called,gl_handle_signal()then callsgl_raw_io(), to resume entry of the input lines on those terminals. - Finally, it restores the signal process mask to how it was when
gl_handle_signal()was called.
Note that the process is suspended or terminated using the original signal that was caught, rather than using the uncatchable SIGSTOP and SIGKILL signals. This is important, because when a process is suspended or terminated, the parent of the process may wish to use the status value returned by the wait() system call to figure out which signal was responsible. In particular, most shells use this information to print a corresponding message to the terminal. Users would be rightly confused if when their process received a SIGPIPE signal, the program responded by sending itself a SIGKILL signal, and the shell then printed out the provocative statement, "Killed!". π like bestie no that's not what happened at all.
β¨ INTERRUPTING THE EVENT LOOP β¨
If a signal is caught and handled while the application's event loop is waiting in select() or poll(), these functions will be aborted with errno set to EINTR. When this happens the event loop should call gl_pending_io(), before calling select() or poll() again. It should then arrange for select() or poll() to wait for the type of I/O that this reports. This is necessary, because any signal handler which calls gl_handle_signal(), will frequently change the type of I/O that gl_get_line() is waiting for. π
Unfortunately, if a signal arrives between the statements which configure the arguments of select() or poll() and the calls to these functions, then the signal will not be seen by these functions, which will then not be aborted. If these functions are waiting for keyboard input from the user when the signal is received, and the signal handler arranges to redraw the input line to accommodate a terminal resize or the resumption of the process, then this redisplay will be end up being delayed until the user hits the next key. Apart from puzzling the user, this clearly isn't a serious problem. However there is a way, albeit complicated, to completely avoid this race condition. The following steps illustrate this.
- Block all of the signals that
gl_get_line()catches, by passing the signal set returned bygl_list_signals()tosigprocmask(). - Call
gl_pending_io()and set up the arguments ofselect()orpoll()accordingly. - Call
sigsetjmp()with a non-zero savesigs argument. - Initially this
sigsetjmp()statement will return zero, indicating that control isn't resuming there after a matching call tosiglongjmp(). - Replace all of the handlers of the signals that
gl_get_line()is configured to catch, with a signal handler that first records the number of the signal that was caught, in a file-scope variable, then callssiglongjmp()with a non-zero value argument, to return execution to the abovesigsetjmp()statement. Registering these signal handlers can conveniently be done using thegl_tty_signals()function. - Set the file-scope variable that the above signal handler uses to record any signal that is caught to
-1, so that we can check whether a signal was caught by seeing if it contains a valid signal number. - Now unblock the signals that were blocked in step 1. Any signal that was received by the process in between step 1 and now will now be delivered, and trigger our signal handler, as will any signal that is received until we block these signals again.
- Now call
select()orpoll(). - When
select()returns, again block the signals that were unblocked in step 7.
If a signal is arrived any time during the above steps, our signal handler will be triggered and cause control to return to the sigsetjmp() statement, where this time, sigsetjmp() will return non-zero, indicating that a signal was caught. When this happens we simply skip the above block of statements, and continue with the following statements, which are executed regardless of whether or not a signal is caught. Note that when sigsetjmp() returns, regardless of why it returned, the process signal mask is returned to how it was when sigsetjmp() was called. Thus the following statements are always executed with all of our signals blocked.
- Reinstate the signal handlers that were displaced in step 5.
- Check whether a signal was caught, by checking the file-scope variable that the signal handler records signal numbers in.
- If a signal was caught, send this signal to the application again, and unblock just this signal, so that it invokes the signal handler which we just reinstated in step 10.
- Unblock all of the signals that were blocked in step 7.
Since this is complicated, note that demo3.c includes a working example of how to do this. The method used there however, is more general than the above. What it provides is a wrapper function around select() which encompasses steps 3 to 11. In this wrapper, rather than use gl_list_signals() to figure out the signals to block, and and gl_tty_signals() to assign and revert signal handlers, one of its arguments is a sigset_t which specifies which signals to block and assign signal handlers to. This function thus doesn't depend on gl_get_line() and can thus be used in other situations where race-condition-free signal handling is required. π
π¦ SIGNALS CAUGHT BY GL_GET_LINE π¦
Since the application is expected to handle signals in non-blocking server mode, gl_get_line() doesn't attempt to duplicate this when it is being called. If one of the signals that it is configured to catch is sent to the application while gl_get_line() is being called, gl_get_line() reinstates the caller's signal handlers, then just before returning, re-sends the signal to the process to let the application's signal handler handle it. If the process isn't terminated by this signal, gl_get_line() returns NULL, and a following call to gl_return_status() returns the enumerated value GLR_SIGNAL.
π ABORTING LINE INPUT π
Often, rather than letting it terminate the process, applications respond to the SIGINT user-interrupt signal by aborting the current input line. The way to do this in non-blocking server-I/O mode is to not call gl_handle_signal() when this signal is caught, but instead to call the gl_abandon_line().
void gl_abandon_line(GetLine *gl);
This function arranges that when gl_get_line() is next called, it first flushes any pending output to the terminal, then discardes the current input line, outputs a new prompt on the next line, and finally starts accepting input of a new input line from the user. fresh start, we love to see it π
π SIGNAL SAFE FUNCTIONS π
Provided that certain rules are followed, the following functions can have been written to be safely callable from signal handlers. Other functions in this library should not be called from signal handlers.
gl_normal_io()gl_raw_io()gl_handle_signal()gl_abandon_line()
In order for this to be true, all signal handlers that call these functions must be registered in such a way that only one instance of any one of them can be running at one time. The way to do this is to use the POSIX sigaction() function to register all signal handlers, and when doing this, use the sa_mask member of the corresponding sigaction structure, to indicate that all of the signals who's handlers invoke the above functions, should be blocked when the current signal is being handled. This prevents two signal handlers from operating on a GetLine object at the same time. no fighting over the GetLine pls π
To prevent signal handlers from accessing a GetLine object while gl_get_line() or any of its associated public functions are operating on it, all public functions associated with gl_get_line(), including gl_get_line() itself, temporarily block the delivery of signals when they are accessing GetLine objects. Beware that the only signals that they block are the signals that gl_get_line() is currently configured to catch, so be sure that if you call any of the above functions from signal handlers, that the signals that these handlers are assigned to are configured to be caught by gl_get_line() (see gl_trap_signal()).
β° USING TIMEOUTS TO POLL β°
If instead of using select() or poll() to wait for I/O, your application just needs to get out of gl_get_line() periodically to briefly do something else before returning to accept input from the user, this can be done in non-blocking server mode by using the gl_inactivity_timeout() function (see gl_get_line(3)), to specify that a callback function that returns GLTO_CONTINUE should be called whenever gl_get_line() has been waiting for I/O for more than a specified amount of time.
When this callback is triggered, gl_get_line() will return NULL, and a following call to gl_return_status() will return GLR_BLOCKED.
Beware thatgl_get_line()won't return until the user hasn't typed a key for the specified interval, so if the interval is long, and the user keeps typing,gl_get_line()may not return for a while. In other words there is no guarantee that it will return in the time specified. π¬ yeah it's giving "approximately", not "on the dot".
π THE SERVER DEMO PROGRAM π
The demo3 program that is distributed with the library, provides a working example of how to use non-blocking server I/O mode in a real program. As far as the user is concerned, this program operates identically to the main demo program (called demo), except that whereas the main demo program uses the normal blocking I/O mode, demo3 using non-blocking I/O and an external event loop. The source code can be found in demo3.c, and the comments therein explain the various steps. go read it bestie, it's literally all there π«Ά
π FILES π
Okay so here's where these two iconic little files live, bestie β memorize them, they're your new besties:
libtecla.aβ the tecla library itself. the whole vibe, compiled and ready πlibtecla.hβ the tecla header file. you gotta#includethis if you want in on the action β¨
π SEE ALSO π
the whole tecla cinematic universe, fr fr β go read these next, no cap:
π AUTHOR π
the one and only Martin Shepherd (mcs@astro.caltech.edu) β legend behavior, honestly. he built the whole thing and we are simply living in it π«Ά
and that's the whole page, bestie!! you made it to the end, which is lowkey main character energy π this was gl_io_mode(3), straight outta the libtecla manual β go forth and do non-blocking I/O like the icon you are. mwah π
β¨
π¦ where this page comes from
- debian bookworm: libtecla-dev 1.6.3-3+b1 Β· BSDlike
- debian trixie: libtecla-dev 1.6.3-3.1 Β· BSDlike
- ubuntu jammy: libtecla-dev 1.6.3-3 Β· BSDlike
- ubuntu noble: libtecla-dev 1.6.3-3.1build1 Β· BSDlike
- ubuntu questing: libtecla-dev 1.6.3-3.1build1
- ubuntu resolute: libtecla-dev 1.6.3-4 Β· BSDlike
- ubuntu stonking: libtecla-dev 1.6.3-5 Β· BSDlike
- Copyright (c) 2002, 2003, 2004, 2012 by Martin C. Shepherd
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms