setcontext was specified in POSIX.1-2001 and the Single Unix Specification, version 2, but not all Unix-like operating systems provide them. POSIX.1-2004 obsoleted these functions,1 and in POSIX.1-2008 they were removed, with POSIX Threads indicated as a possible replacement.
The functions and associated types are defined in the ucontext.h system header file. This includes the ucontext_t type, with which all four functions operate:
uc_link points to the context which will be resumed when the current context exits, if the context was created with makecontext (a secondary context). uc_sigmask is used to store the set of signals blocked in the context, and uc_stack is the stack used by the context. uc_mcontext stores execution state, including all registers and CPU flags, the instruction pointer, and the stack pointer; mcontext_t is an opaque type.
The functions are:
The example below demonstrates an iterator using setcontext.
NOTE: this example is not correct,2 but may work as intended in some cases. The function makecontext requires additional parameters to be type int, but the example passes pointers. Thus, the example may fail on 64-bit machines (specifically LP64-architectures, where sizeof(void*) > sizeof(int)). This problem can be worked around by breaking up and reconstructing 64-bit values, but that introduces a performance penalty.
On architectures where int and pointer types are the same size (e.g., x86-32, where both types are 32 bits), you may be able to get away with passing pointers as arguments to makecontext() following argc. However, doing this is not guaranteed to be portable, is undefined according to the standards, and won't work on architectures where pointers are larger than ints. Nevertheless, starting with version 2.8, glibc makes some changes to makecontext(3), to permit this on some 64-bit architectures (e.g., x86-64).
For get and set context, a smaller context can be handy:
This makes an infinite loop because context holds the program counter.
The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 Edition [1] http://www.opengroup.org/onlinepubs/009695399/functions/makecontext.html ↩