Setjmp.h

Setjmp.h

setjmp.h is a header defined in the C standard library to provide "non-local jumps" (control flow) outside of the normal function call and return sequence. The paired functions setjmp and longjmp provide this functionality through first saving the environment with setjmp to which longjmp can "jump" from a point elsewhere in the program.

The typical use for setjmp/longjmp is for exception handling — by calling longjmp, the program can jump out of many levels of nested function calls without having to go to the trouble of setting flag variables which need to be checked in each function. A problem with the use of setjmp/longjmp is that cleanup (closing file descriptors, flushing buffers, freeing heap-allocated memory, etc.) will not be conducted.

On systems that support signal handling, POSIX.1 does not specify whether setjmp and longjmp save or restore the current set of blocked signals — if a program employs signal handling it should use POSIX's sigsetjmp/siglongjmp.

Compared to mechanisms in higher-level programming languages such as Python, Java, C++, C#, and particularly in older high-level languages such as Algol 60 and Common Lisp, the setjmp/longjmp technique is archaic. These languages provide more powerful exception handling techniques, while languages such as Scheme and Haskell provide even more general continuation-handling constructs.

Member functions

setjmp saves the current execution state into a structure of type jmp_buf; later, a longjmp call can transfer control to the point immediately after the call to setjmp. The (apparent) return value from setjmp indicates whether control reached that point normally or from a call to longjmp. This leads to a common idiom: if( setjmp(x) ){/* handle longjmp(x) */}.

Member types

The C99 Rationale describes jmp_buf as being an array type for backwards compatibility; existing code refers to jmp_buf storage locations by name (without the & address-of operator), which is only possible for array types. [http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf C99 Rationale, version 5.10, April 2003] , section 7.13]

Caveats

If the function in which setjmp/sigsetjmp was called returns, it is no longer possible to safely use longjmp/siglongjmp with the corresponding jmp_buf/sigjmp_buf object. This is because the stack frame is invalidated when the function returns. Calling longjmp/siglongjmp restores the stack pointer, which—because the function returned—would point to a non-existent and potentially overwritten/corrupted stack frame. [ [http://www.cs.utk.edu/~huangj/cs360/360/notes/Setjmp/lecture.html CS360 Lecture Notes — Setjmp and Longjmp] ] [ [http://www.uwm.edu/cgi-bin/IMT/wwwman?topic=setjmp(3)&msection= setjmp(3)] ]

Similarly, C99 does not require that longjmp/siglongjmp preserve the current stack frame. This means that jumping into a function which was exited via a call to longjmp/siglongjmp is undefined. [ [http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf ISO/IEC 9899:1999] , 2005, 7.13.2.1:2 and footnote 211] However, most implementations of longjmp/siglongjmp leave the stack frame intact, allowing setjmp/sigsetjmp and longjmp/siglongjmp to be used to jump back-and-forth between two or more functions—a feature exploited for multitasking.

Example

In this example, setjmp is used to bracket exception handling, like try in some other languages. The call to longjmp is analogous to a throw statement, allowing an exception to return an error status directly to the setjmp. The following code adheres to the 1999 ISO C standard and SUS by invoking setjmp in a limited range of contexts:


Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • Setjmp — Связать? setjmp  функция в языках программирования Си (язык программирования) и C++. Сохранаяет текущий контекст выполнения программы для обеспечения дальнейшего восстановления. Содержание …   Википедия

  • setjmp.h — C Standard Library Data types Character classification Strings Mathematics File input/output Date/time Localization …   Wikipedia

  • Setjmp.h — Este artículo o sección necesita ser wikificado con un formato acorde a las convenciones de estilo. Por favor, edítalo para que las cumpla. Mientras tanto, no elimines este aviso puesto el 8 de junio de 2011. También puedes ayudar wikificando… …   Wikipedia Español

  • setjmp.h — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h …   Википедия

  • Setjmp (функция) — setjmp сохранаяет текущий контекст выполнения программы для обеспечения дальнейшего восстановления Содержание 1 Синтаксис 2 Описание 3 Возвращаемое значение 4 См. также …   Википедия

  • Longjmp — Эту страницу предлагается объединить с setjmp.h. Пояснение причин и обсуждение на странице Википедия:К объединению/10 октября 2011. Обсуждение длится одну неделю (или дольше, если оно идёт медленно). Дата начала …   Википедия

  • Coroutine — Coroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Coroutines are well suited for implementing more familiar program components such as …   Wikipedia

  • C standard library — The C Standard Library consists of a set of sections of the ANSI C standard in the programming language C. They describe a collection of headers and library routines used to implement common operations such as input/output[1] and string handling …   Wikipedia

  • Funciones de la biblioteca estándar de C — Anexo:Funciones de la biblioteca estándar de C Saltar a navegación, búsqueda El propósito de este artículo es proporcionar un listado alfabético de todas las funciones de la biblioteca estándar de C, y unas pocas funciones no estándar. Contenido… …   Wikipedia Español

  • Стандартная библиотека языка Си — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h …   Википедия

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”