Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 7.10 setjmpandlongjmpFunctions 217


Whenmainis executed, we callsetjmp,which records whatever information it needs
to in the variablejmpbuffer and returns 0. We then calldo_line,which calls
cmd_add,and assume that an error of some form is detected. Beforethe call to
longjmpincmd_add,the stack looks like that in Figure7.10. Butlongjmpcauses the
stack to be ‘‘unwound’’back to themainfunction, throwing away the stack frames for
cmd_addanddo_line(Figure7.12). Callinglongjmpcauses thesetjmpinmainto
return, but this time it returns with a value of 1 (the second argument forlongjmp).

stack frame
formain

bottom of stack higher address

lower address

direction of
stack growth

Figure 7.12 Stack frame afterlongjmphas been called

Automatic, Register,and Volatile Variables


We’ve seen what the stack looks like after callinglongjmp.The next question is, ‘‘What
arethe states of the automatic variables and register variables in themainfunction?’’
When we return tomainas a result of thelongjmp, do these variables have values
corresponding to those when thesetjmpwas previously called (i.e., aretheir values
rolled back), or aretheir values left alone so that their values arewhatever they were
when do_line was called (which caused cmd_add to be called, which caused
longjmp to be called)? Unfortunately,the answer is ‘‘It depends.’’Most
implementations do not try to roll back these automatic variables and register variables,
but the standards say only that their values areindeterminate. If you have an automatic
variable that you don’t want rolled back, define it with thevolatile attribute.
Variables that aredeclared as global or static areleft alone whenlongjmpis executed.

Example


The program in Figure7.13 demonstrates the different behavior that can be seen with
automatic, global, register,static, and volatile variables after callinglongjmp.
Free download pdf