You think GOTO statement is bad? Wait until you learn about setjmp() and longjmp()!

Follow

@vaporeon_ the unix programming environment actually uses them in some example code, in a book meant fur beginners to unix, not to mention purrogramming lol

@aescling Yep! They have the example that a text editor, if interrupted while doing a long printout (who of us hasn't accidentally cat-ed a huge file and then regretted it...), shouldn't exit, but should jump back to the main loop (without losing the work). Page 227, this is the code:

#include <signal.h>
#include <setjmp.h>
jmp_buf sjbuf;

main()
{
int onintr();

if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, onintr);
setjmp(sjbuf); /* save current stack position */

for (;;) {
/* main processing loop */
}
...
}

onintr() /* reset if interrupted */
{
signal(SIGINT, onintr); /* reset for next interrupt */
printf("\nInterrupt\n");
longjmp(sjbuf, 0); /* return to saved state */
}

It makes sense to me! How would you solve this without setjmp() / longjmp()?

@aescling I really liked that book, it made me better at shell programming and at UNIX in general

Sign in to participate in the conversation
📟🐱 GlitchCat

A small, community‐oriented Mastodon‐compatible Fediverse (GlitchSoc) instance managed as a joint venture between the cat and KIBI families.