setjmp()

Save the calling environment for longjmp()

Synopsis:

#include <setjmp.h>

int setjmp( jmp_buf env );

Since:

BlackBerry 10.0.0

Arguments:

env
A buffer where the function can save the calling environment.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The setjmp() function saves the calling environment in its env argument for use by the longjmp() function.

Error handling can be implemented by using setjmp() to record the point to return to following an error. When an error is detected in a function, that function uses longjmp() to jump back to the recorded position. The original function that called setjmp() must still be active (that is, it can't have returned to the function that called it).

Be careful to ensure that any resources (allocated memory, opened files, etc) are cleaned up properly.

DANGER
Do not use longjmp() or siglongjmp() to restore an environment saved by a call to setjmp() or sigsetjmp() in another thread. If you're lucky, your application will crash; if not, it'll look as if it works for a while, until random scribbling on the stack causes it to crash.

Returns:

Zero on the first call, or nonzero if the return is the result of a call to the longjmp() function.

Examples:

#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>

jmp_buf env;

void rtn( void )
{
    printf( "about to longjmp()\n" );
    longjmp( env, 14 );
}

int main( void )
{
    int ret_val;

    ret_val = setjmp( env );

    if( ret_val == 0 ) {
        printf( "after setjmp(): %d\n", ret_val );
        rtn();
        printf( "back from rtn(): %d\n", ret_val );
    } else {
        printf( "back from longjmp(): %d\n", ret_val );
    }
    
    return EXIT_SUCCESS;
}

produces the output:

after setjmp(): 0
about to longjmp()
back from longjmp(): 14

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus