setjmp()

QNX SDP8.0C Library ReferenceAPIDeveloper

Save the calling environment for longjmp()

Synopsis:

#include <setjmp.h>

int setjmp( jmp_buf env );

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.

Note:
Don't use this function in an expression that's an argument to a function. Since it is a macro and it evaluates the argument more than once, doing so may result in unexpected behaviour.
DANGER:
Don't 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.
CAUTION:
The setjmp() function does not save the thread's signal mask and longjmp() does not restore it. If you need to save and restore the thread's signal mask, use sigsetjmp() and siglongjmp() instead.

Returns:

Zero if invoked directly, 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 pointNo
Signal handlerYes
ThreadYes
Page updated: