Node:System V contexts, Previous:Non-Local Exits and Signals, Up:Non-Local Exits
The Unix standard one more set of function to control the execution path
and these functions are more powerful than those discussed in this
chapter so far. These function were part of the original System V
API and by this route were added to the Unix API. Beside on branded
Unix implementations these interfaces are not widely available. Not all
platforms and/or architectures the GNU C Library is available on provide
this interface. Use configure
to detect the availability.
Similar to the jmp_buf
and sigjmp_buf
types used for the
variables to contain the state of the longjmp
functions the
interfaces of interest here have an appropriate type as well. Objects
of this type are normally much larger since more information is
contained. The type is also used in a few more places as we will see.
The types and functions described in this section are all defined and
declared respectively in the ucontext.h
header file.
ucontext_t | Data Type |
The
|
Objects of this type have to be created by the user. The initialization and modification happens through one of the following functions:
int getcontext (ucontext_t *ucp) | Function |
The getcontext function initializes the variable pointed to by
ucp with the context of the calling thread. The context contains
the content of the registers, the signal mask, and the current stack.
Executing the contents would start at the point where the
getcontext call just returned.
The function returns |
The getcontext
function is similar to setjmp
but it does
not provide an indication of whether the function returns for the first
time or whether the initialized context was used and the execution is
resumed at just that point. If this is necessary the user has to take
determine this herself. This must be done carefully since the context
contains registers which might contain register variables. This is a
good situation to define variables with volatile
.
Once the context variable is initialized it can be used as is or it can
be modified. The latter is normally done to implement co-routines or
similar constructs. The makecontext
function is what has to be
used to do that.
void makecontext (ucontext_t *ucp, void (*func) (void), int argc, ...) | Function |
The ucp parameter passed to the Before the call to this function the The |
While allocating the memory for the stack one has to be careful. Most modern processors keep track of whether a certain memory region is allowed to contain code which is executed or not. Data segments and heap memory is normally not tagged to allow this. The result is that programs would fail. Examples for such code include the calling sequences the GNU C compiler generates for calls to nested functions. Safe ways to allocate stacks correctly include using memory on the original threads stack or explicitly allocate memory tagged for execution using (see Memory-mapped I/O).
Compatibility note: The current Unix standard is very imprecise
about the way the stack is allocated. All implementations seem to agree
that the uc_stack
element must be used but the values stored in
the elements of the stack_t
value are unclear. The GNU C library
and most other Unix implementations require the ss_sp
value of
the uc_stack
element to point to the base of the memory region
allocated for the stack and the size of the memory region is stored in
ss_size
. There are implements out there which require
ss_sp
to be set to the value the stack pointer will have (which
can depending on the direction the stack grows be different). This
difference makes the makecontext
function hard to use and it
requires detection of the platform at compile time.
int setcontext (const ucontext_t *ucp) | Function |
The If the context was created by If the context was modified with a call to Since the context contains information about the stack no two threads should use the same context at the same time. The result in most cases would be disastrous. The |
The setcontext
function simply replaces the current context with
the one described by the ucp parameter. This is often useful but
there are situations where the current context has to be preserved.
int swapcontext (ucontext_t *restrict oucp, const ucontext_t *restrict ucp) | Function |
The Once the current context is saved the context described in ucp is installed and execution continues as described in this context. If |
The easiest way to use the context handling functions is as a
replacement for setjmp
and longjmp
. The context contains
on most platforms more information which might lead to less surprises
but this also means using these functions is more expensive (beside
being less portable).
int random_search (int n, int (*fp) (int, ucontext_t *)) { volatile int cnt = 0; ucontext_t uc; /* Safe current context. */ if (getcontext (&uc) < 0) return -1; /* If we have not tried n times try again. */ if (cnt++ < n) /* Call the function with a new random number and the context. */ if (fp (rand (), &uc) != 0) /* We found what we were looking for. */ return 1; /* Not found. */ return 0; }
Using contexts in such a way enables emulating exception handling. The search functions passed in the fp parameter could be very large, nested, and complex which would make it complicated (or at least would require a lot of code) to leave the function with an error value which has to be passed down to the caller. By using the context it is possible to leave the search function in one step and allow restarting the search which also has the nice side effect that it can be significantly faster.
Something which is harder to implement with setjmp
and
longjmp
is to switch temporarily to a different execution path
and then resume where execution was stopped.
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <ucontext.h> #include <sys/time.h> /* Set by the signal handler. */ static volatile int expired; /* The contexts. */ static ucontext_t uc[3]; /* We do only a certain number of switches. */ static int switches; /* This is the function doing the work. It is just a skeleton, real code has to be filled in. */ static void f (int n) { int m = 0; while (1) { /* This is where the work would be done. */ if (++m % 100 == 0) { putchar ('.'); fflush (stdout); } /* Regularly the expire variable must be checked. */ if (expired) { /* We do not want the program to run forever. */ if (++switches == 20) return; printf ("\nswitching from %d to %d\n", n, 3 - n); expired = 0; /* Switch to the other context, saving the current one. */ swapcontext (&uc[n], &uc[3 - n]); } } } /* This is the signal handler which simply set the variable. */ void handler (int signal) { expired = 1; } int main (void) { struct sigaction sa; struct itimerval it; char st1[8192]; char st2[8192]; /* Initialize the data structures for the interval timer. */ sa.sa_flags = SA_RESTART; sigfillset (&sa.sa_mask); sa.sa_handler = handler; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 1; it.it_value = it.it_interval; /* Install the timer and get the context we can manipulate. */ if (sigaction (SIGPROF, &sa, NULL) < 0 || setitimer (ITIMER_PROF, &it, NULL) < 0 || getcontext (&uc[1]) == -1 || getcontext (&uc[2]) == -1) abort (); /* Create a context with a separate stack which causes the functionf
to be call with the parameter1
. Note that theuc_link
points to the main context which will cause the program to terminate once the function return. */ uc[1].uc_link = &uc[0]; uc[1].uc_stack.ss_sp = st1; uc[1].uc_stack.ss_size = sizeof st1; makecontext (&uc[1], (void (*) (void)) f, 1, 1); /* Similarly, but2
is passed as the parameter tof
. */ uc[2].uc_link = &uc[0]; uc[2].uc_stack.ss_sp = st2; uc[2].uc_stack.ss_size = sizeof st2; makecontext (&uc[2], (void (*) (void)) f, 1, 2); /* Start running. */ swapcontext (&uc[0], &uc[1]); putchar ('\n'); return 0; }
This an example how the context functions can be used to implement
co-routines or cooperative multi-threading. All that has to be done is
to call every once in a while swapcontext
to continue running a
different context. It is not allowed to do the context switching from
the signal handler directly since neither setcontext
nor
swapcontext
are functions which can be called from a signal
handler. But setting a variable in the signal handler and checking it
in the body of the functions which are executed. Since
swapcontext
is saving the current context it is possible to have
multiple different scheduling points in the code. Execution will always
resume where it was left.