Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 7.10 setjmpandlongjmpFunctions 215


stack frame
formain

stack frame
fordo_line

stack frame
forcmd_add

bottom of stack higher address

lower address

direction of
stack growth

Figure 7.10Stack frames aftercmd_addhas been called

Storage for the automatic variables is within the stack frame for each function. The
arraylineis in the stack frame formain,the integercmdis in the stack frame for
do_line,and the integertokenis in the stack frame forcmd_add.
As we’ve said, this type of arrangement of the stack is typical, but not required.
Stacks do not have to grow towardlower memory addresses. On systems that don’t
have built-in hardwaresupport for stacks, a C implementation might use a linked list
for its stack frames.
The coding problem that’s often encountered with programs like the one shown in
Figure7.9 is how to handle nonfatal errors. For example, if thecmd_addfunction
encounters an error — say, an invalid number—itmight want to print an error message,
ignorethe rest of the input line, and return to themainfunction to read the next input
line. But when we’redeeply nested numerous levels down from themainfunction, this
is difficult to do in C. (In this example, thecmd_addfunction is only two levels down
frommain,but it’s not uncommon to be five or morelevels down from the point to
which we want to return.) It becomes messy if we have to code each function with a
special return value that tells it to return one level.
The solution to this problem is to use a nonlocalgoto:thesetjmpandlongjmp
functions. The adjective ‘‘nonlocal’’indicates that we’renot doing a normal Cgoto
statement within a function; instead, we’rebranching back through the call frames to a
function that is in the call path of the current function.

#include <setjmp.h>

int setjmp(jmp_bufenv);

Returns: 0 if called directly,nonzero if returning from a call tolongjmp

void longjmp(jmp_bufenv,intval);
Free download pdf