/usr/share/doc/glibc-doc/html/libc_23.html is in glibc-doc 2.15-0ubuntu10.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html401/loose.dtd">
<html>
<!-- This file documents the GNU C library.
This is Edition 0.13, last updated 2011-07-19,
of The GNU C Library Reference Manual, for version
2.14 (Ubuntu EGLIBC 2.15-0ubuntu10) .
Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
2003, 2007, 2008, 2010, 2011 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software Needs Free Documentation"
and "GNU Lesser General Public License", the Front-Cover texts being
"A GNU Manual", and with the Back-Cover Texts as in (a) below. A
copy of the license is included in the section entitled "GNU Free
Documentation License".
(a) The FSF's Back-Cover Text is: "You have the freedom to
copy and modify this GNU manual. Buying copies from the FSF
supports it in developing GNU and promoting software freedom."
-->
<!-- Created on April 20, 2012 by texi2html 1.82
texi2html was written by:
Lionel Cons <Lionel.Cons@cern.ch> (original author)
Karl Berry <karl@freefriends.org>
Olaf Bachmann <obachman@mathematik.uni-kl.de>
and many others.
Maintained by: Many creative people.
Send bugs and suggestions to <texi2html-bug@nongnu.org>
-->
<head>
<title>The GNU C Library: 23. Non-Local Exits</title>
<meta name="description" content="The GNU C Library: 23. Non-Local Exits">
<meta name="keywords" content="The GNU C Library: 23. Non-Local Exits">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html 1.82">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.roman {font-family:serif; font-weight:normal;}
span.sansserif {font-family:sans-serif; font-weight:normal;}
ul.toc {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Non_002dLocal-Exits"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="libc_22.html#Processor-Resources" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Intro" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc_22.html#Resource-Usage-And-Limitation" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Non_002dLocal-Exits-1"></a>
<h1 class="chapter">23. Non-Local Exits</h1>
<a name="index-non_002dlocal-exits"></a>
<a name="index-long-jumps"></a>
<p>Sometimes when your program detects an unusual situation inside a deeply
nested set of function calls, you would like to be able to immediately
return to an outer level of control. This section describes how you can
do such <em>non-local exits</em> using the <code>setjmp</code> and <code>longjmp</code>
functions.
</p>
<table class="menu" border="0" cellspacing="0">
<tr><td align="left" valign="top"><a href="#Non_002dLocal-Intro">23.1 Introduction to Non-Local Exits</a></td><td> </td><td align="left" valign="top"> When and how to use these facilities.
</td></tr>
<tr><td align="left" valign="top"><a href="#Non_002dLocal-Details">23.2 Details of Non-Local Exits</a></td><td> </td><td align="left" valign="top"> Functions for non-local exits.
</td></tr>
<tr><td align="left" valign="top"><a href="#Non_002dLocal-Exits-and-Signals">23.3 Non-Local Exits and Signals</a></td><td> </td><td align="left" valign="top"> Portability issues.
</td></tr>
<tr><td align="left" valign="top"><a href="#System-V-contexts">23.4 Complete Context Control</a></td><td> </td><td align="left" valign="top"> Complete context control a la System V.
</td></tr>
</table>
<hr size="6">
<a name="Non_002dLocal-Intro"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Details" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Introduction-to-Non_002dLocal-Exits"></a>
<h2 class="section">23.1 Introduction to Non-Local Exits</h2>
<p>As an example of a situation where a non-local exit can be useful,
suppose you have an interactive program that has a “main loop” that
prompts for and executes commands. Suppose the “read” command reads
input from a file, doing some lexical analysis and parsing of the input
while processing it. If a low-level input error is detected, it would
be useful to be able to return immediately to the “main loop” instead
of having to make each of the lexical analysis, parsing, and processing
phases all have to explicitly deal with error situations initially
detected by nested calls.
</p>
<p>(On the other hand, if each of these phases has to do a substantial
amount of cleanup when it exits—such as closing files, deallocating
buffers or other data structures, and the like—then it can be more
appropriate to do a normal return and have each phase do its own
cleanup, because a non-local exit would bypass the intervening phases and
their associated cleanup code entirely. Alternatively, you could use a
non-local exit but do the cleanup explicitly either before or after
returning to the “main loop”.)
</p>
<p>In some ways, a non-local exit is similar to using the ‘<samp>return</samp>’
statement to return from a function. But while ‘<samp>return</samp>’ abandons
only a single function call, transferring control back to the point at
which it was called, a non-local exit can potentially abandon many
levels of nested function calls.
</p>
<p>You identify return points for non-local exits by calling the function
<code>setjmp</code>. This function saves information about the execution
environment in which the call to <code>setjmp</code> appears in an object of
type <code>jmp_buf</code>. Execution of the program continues normally after
the call to <code>setjmp</code>, but if an exit is later made to this return
point by calling <code>longjmp</code> with the corresponding <code>jmp_buf</code>
object, control is transferred back to the point where <code>setjmp</code> was
called. The return value from <code>setjmp</code> is used to distinguish
between an ordinary return and a return made by a call to
<code>longjmp</code>, so calls to <code>setjmp</code> usually appear in an ‘<samp>if</samp>’
statement.
</p>
<p>Here is how the example program described above might be set up:
</p>
<table><tr><td> </td><td><pre class="smallexample">#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
jmp_buf main_loop;
void
abort_to_main_loop (int status)
{
longjmp (main_loop, status);
}
int
main (void)
{
while (1)
if (setjmp (main_loop))
puts ("Back at main loop....");
else
do_command ();
}
void
do_command (void)
{
char buffer[128];
if (fgets (buffer, 128, stdin) == NULL)
abort_to_main_loop (-1);
else
exit (EXIT_SUCCESS);
}
</pre></td></tr></table>
<p>The function <code>abort_to_main_loop</code> causes an immediate transfer of
control back to the main loop of the program, no matter where it is
called from.
</p>
<p>The flow of control inside the <code>main</code> function may appear a little
mysterious at first, but it is actually a common idiom with
<code>setjmp</code>. A normal call to <code>setjmp</code> returns zero, so the
“else” clause of the conditional is executed. If
<code>abort_to_main_loop</code> is called somewhere within the execution of
<code>do_command</code>, then it actually appears as if the <em>same</em> call
to <code>setjmp</code> in <code>main</code> were returning a second time with a value
of <code>-1</code>.
</p>
<p>So, the general pattern for using <code>setjmp</code> looks something like:
</p>
<table><tr><td> </td><td><pre class="smallexample">if (setjmp (<var>buffer</var>))
/* <span class="roman">Code to clean up after premature return.</span> */
…
else
/* <span class="roman">Code to be executed normally after setting up the return point.</span> */
…
</pre></td></tr></table>
<hr size="6">
<a name="Non_002dLocal-Details"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="#Non_002dLocal-Intro" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits-and-Signals" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Details-of-Non_002dLocal-Exits"></a>
<h2 class="section">23.2 Details of Non-Local Exits</h2>
<p>Here are the details on the functions and data structures used for
performing non-local exits. These facilities are declared in
‘<tt>setjmp.h</tt>’.
<a name="index-setjmp_002eh"></a>
</p>
<dl>
<dt><a name="index-jmp_005fbuf"></a><u>Data Type:</u> <b>jmp_buf</b></dt>
<dd><p>Objects of type <code>jmp_buf</code> hold the state information to
be restored by a non-local exit. The contents of a <code>jmp_buf</code>
identify a specific place to return to.
</p></dd></dl>
<dl>
<dt><a name="index-setjmp"></a><u>Macro:</u> int <b>setjmp</b><i> (jmp_buf <var>state</var>)</i></dt>
<dd><p>When called normally, <code>setjmp</code> stores information about the
execution state of the program in <var>state</var> and returns zero. If
<code>longjmp</code> is later used to perform a non-local exit to this
<var>state</var>, <code>setjmp</code> returns a nonzero value.
</p></dd></dl>
<dl>
<dt><a name="index-longjmp-1"></a><u>Function:</u> void <b>longjmp</b><i> (jmp_buf <var>state</var>, int <var>value</var>)</i></dt>
<dd><p>This function restores current execution to the state saved in
<var>state</var>, and continues execution from the call to <code>setjmp</code> that
established that return point. Returning from <code>setjmp</code> by means of
<code>longjmp</code> returns the <var>value</var> argument that was passed to
<code>longjmp</code>, rather than <code>0</code>. (But if <var>value</var> is given as
<code>0</code>, <code>setjmp</code> returns <code>1</code>).
</p></dd></dl>
<p>There are a lot of obscure but important restrictions on the use of
<code>setjmp</code> and <code>longjmp</code>. Most of these restrictions are
present because non-local exits require a fair amount of magic on the
part of the C compiler and can interact with other parts of the language
in strange ways.
</p>
<p>The <code>setjmp</code> function is actually a macro without an actual
function definition, so you shouldn’t try to ‘<samp>#undef</samp>’ it or take
its address. In addition, calls to <code>setjmp</code> are safe in only the
following contexts:
</p>
<ul>
<li>
As the test expression of a selection or iteration
statement (such as ‘<samp>if</samp>’, ‘<samp>switch</samp>’, or ‘<samp>while</samp>’).
</li><li>
As one operand of a equality or comparison operator that appears as the
test expression of a selection or iteration statement. The other
operand must be an integer constant expression.
</li><li>
As the operand of a unary ‘<samp>!</samp>’ operator, that appears as the
test expression of a selection or iteration statement.
</li><li>
By itself as an expression statement.
</li></ul>
<p>Return points are valid only during the dynamic extent of the function
that called <code>setjmp</code> to establish them. If you <code>longjmp</code> to
a return point that was established in a function that has already
returned, unpredictable and disastrous things are likely to happen.
</p>
<p>You should use a nonzero <var>value</var> argument to <code>longjmp</code>. While
<code>longjmp</code> refuses to pass back a zero argument as the return value
from <code>setjmp</code>, this is intended as a safety net against accidental
misuse and is not really good programming style.
</p>
<p>When you perform a non-local exit, accessible objects generally retain
whatever values they had at the time <code>longjmp</code> was called. The
exception is that the values of automatic variables local to the
function containing the <code>setjmp</code> call that have been changed since
the call to <code>setjmp</code> are indeterminate, unless you have declared
them <code>volatile</code>.
</p>
<hr size="6">
<a name="Non_002dLocal-Exits-and-Signals"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="#Non_002dLocal-Details" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#System-V-contexts" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Non_002dLocal-Exits-and-Signals-1"></a>
<h2 class="section">23.3 Non-Local Exits and Signals</h2>
<p>In BSD Unix systems, <code>setjmp</code> and <code>longjmp</code> also save and
restore the set of blocked signals; see <a href="libc_24.html#Blocking-Signals">Blocking Signals</a>. However,
the POSIX.1 standard requires <code>setjmp</code> and <code>longjmp</code> not to
change the set of blocked signals, and provides an additional pair of
functions (<code>sigsetjmp</code> and <code>siglongjmp</code>) to get the BSD
behavior.
</p>
<p>The behavior of <code>setjmp</code> and <code>longjmp</code> in the GNU library is
controlled by feature test macros; see <a href="libc_1.html#Feature-Test-Macros">Feature Test Macros</a>. The
default in the GNU system is the POSIX.1 behavior rather than the BSD
behavior.
</p>
<p>The facilities in this section are declared in the header file
‘<tt>setjmp.h</tt>’.
<a name="index-setjmp_002eh-1"></a>
</p>
<dl>
<dt><a name="index-sigjmp_005fbuf"></a><u>Data Type:</u> <b>sigjmp_buf</b></dt>
<dd><p>This is similar to <code>jmp_buf</code>, except that it can also store state
information about the set of blocked signals.
</p></dd></dl>
<dl>
<dt><a name="index-sigsetjmp"></a><u>Function:</u> int <b>sigsetjmp</b><i> (sigjmp_buf <var>state</var>, int <var>savesigs</var>)</i></dt>
<dd><p>This is similar to <code>setjmp</code>. If <var>savesigs</var> is nonzero, the set
of blocked signals is saved in <var>state</var> and will be restored if a
<code>siglongjmp</code> is later performed with this <var>state</var>.
</p></dd></dl>
<dl>
<dt><a name="index-siglongjmp"></a><u>Function:</u> void <b>siglongjmp</b><i> (sigjmp_buf <var>state</var>, int <var>value</var>)</i></dt>
<dd><p>This is similar to <code>longjmp</code> except for the type of its <var>state</var>
argument. If the <code>sigsetjmp</code> call that set this <var>state</var> used a
nonzero <var>savesigs</var> flag, <code>siglongjmp</code> also restores the set of
blocked signals.
</p></dd></dl>
<hr size="6">
<a name="System-V-contexts"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="#Non_002dLocal-Exits-and-Signals" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next section in reading order"> > </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Complete-Context-Control"></a>
<h2 class="section">23.4 Complete Context Control</h2>
<p>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 ‘<tt>configure</tt>’ to detect the availability.
</p>
<p>Similar to the <code>jmp_buf</code> and <code>sigjmp_buf</code> types used for the
variables to contain the state of the <code>longjmp</code> 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 ‘<tt>ucontext.h</tt>’ header file.
</p>
<dl>
<dt><a name="index-ucontext_005ft"></a><u>Data Type:</u> <b>ucontext_t</b></dt>
<dd>
<p>The <code>ucontext_t</code> type is defined as a structure with as least the
following elements:
</p>
<dl compact="compact">
<dt> <code>ucontext_t *uc_link</code></dt>
<dd><p>This is a pointer to the next context structure which is used if the
context described in the current structure returns.
</p>
</dd>
<dt> <code>sigset_t uc_sigmask</code></dt>
<dd><p>Set of signals which are blocked when this context is used.
</p>
</dd>
<dt> <code>stack_t uc_stack</code></dt>
<dd><p>Stack used for this context. The value need not be (and normally is
not) the stack pointer. See section <a href="libc_24.html#Signal-Stack">Using a Separate Signal Stack</a>.
</p>
</dd>
<dt> <code>mcontext_t uc_mcontext</code></dt>
<dd><p>This element contains the actual state of the process. The
<code>mcontext_t</code> type is also defined in this header but the definition
should be treated as opaque. Any use of knowledge of the type makes
applications less portable.
</p>
</dd>
</dl>
</dd></dl>
<p>Objects of this type have to be created by the user. The initialization
and modification happens through one of the following functions:
</p>
<dl>
<dt><a name="index-getcontext"></a><u>Function:</u> int <b>getcontext</b><i> (ucontext_t *<var>ucp</var>)</i></dt>
<dd><p>The <code>getcontext</code> function initializes the variable pointed to by
<var>ucp</var> 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
<code>getcontext</code> call just returned.
</p>
<p>The function returns <code>0</code> if successful. Otherwise it returns
<code>-1</code> and sets <var>errno</var> accordingly.
</p></dd></dl>
<p>The <code>getcontext</code> function is similar to <code>setjmp</code> 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 <code>volatile</code>.
</p>
<p>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 <code>makecontext</code> function is what has to be
used to do that.
</p>
<dl>
<dt><a name="index-makecontext"></a><u>Function:</u> void <b>makecontext</b><i> (ucontext_t *<var>ucp</var>, void (*<var>func</var>) (void), int <var>argc</var>, …)</i></dt>
<dd>
<p>The <var>ucp</var> parameter passed to the <code>makecontext</code> shall be
initialized by a call to <code>getcontext</code>. The context will be
modified to in a way so that if the context is resumed it will start by
calling the function <code>func</code> which gets <var>argc</var> integer arguments
passed. The integer arguments which are to be passed should follow the
<var>argc</var> parameter in the call to <code>makecontext</code>.
</p>
<p>Before the call to this function the <code>uc_stack</code> and <code>uc_link</code>
element of the <var>ucp</var> structure should be initialized. The
<code>uc_stack</code> element describes the stack which is used for this
context. No two contexts which are used at the same time should use the
same memory region for a stack.
</p>
<p>The <code>uc_link</code> element of the object pointed to by <var>ucp</var> should
be a pointer to the context to be executed when the function <var>func</var>
returns or it should be a null pointer. See <code>setcontext</code> for more
information about the exact use.
</p></dd></dl>
<p>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 section <a href="libc_13.html#Memory_002dmapped-I_002fO">Memory-mapped I/O</a>).
</p>
<p><strong>Compatibility note</strong>: The current Unix standard is very imprecise
about the way the stack is allocated. All implementations seem to agree
that the <code>uc_stack</code> element must be used but the values stored in
the elements of the <code>stack_t</code> value are unclear. The GNU C library
and most other Unix implementations require the <code>ss_sp</code> value of
the <code>uc_stack</code> element to point to the base of the memory region
allocated for the stack and the size of the memory region is stored in
<code>ss_size</code>. There are implements out there which require
<code>ss_sp</code> 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 <code>makecontext</code> function hard to use and it
requires detection of the platform at compile time.
</p>
<dl>
<dt><a name="index-setcontext"></a><u>Function:</u> int <b>setcontext</b><i> (const ucontext_t *<var>ucp</var>)</i></dt>
<dd>
<p>The <code>setcontext</code> function restores the context described by
<var>ucp</var>. The context is not modified and can be reused as often as
wanted.
</p>
<p>If the context was created by <code>getcontext</code> execution resumes with
the registers filled with the same values and the same stack as if the
<code>getcontext</code> call just returned.
</p>
<p>If the context was modified with a call to <code>makecontext</code> execution
continues with the function passed to <code>makecontext</code> which gets the
specified parameters passed. If this function returns execution is
resumed in the context which was referenced by the <code>uc_link</code>
element of the context structure passed to <code>makecontext</code> at the
time of the call. If <code>uc_link</code> was a null pointer the application
terminates in this case.
</p>
<p>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.
</p>
<p>The <code>setcontext</code> function does not return unless an error occurred
in which case it returns <code>-1</code>.
</p></dd></dl>
<p>The <code>setcontext</code> function simply replaces the current context with
the one described by the <var>ucp</var> parameter. This is often useful but
there are situations where the current context has to be preserved.
</p>
<dl>
<dt><a name="index-swapcontext"></a><u>Function:</u> int <b>swapcontext</b><i> (ucontext_t *restrict <var>oucp</var>, const ucontext_t *restrict <var>ucp</var>)</i></dt>
<dd>
<p>The <code>swapcontext</code> function is similar to <code>setcontext</code> but
instead of just replacing the current context the latter is first saved
in the object pointed to by <var>oucp</var> as if this was a call to
<code>getcontext</code>. The saved context would resume after the call to
<code>swapcontext</code>.
</p>
<p>Once the current context is saved the context described in <var>ucp</var> is
installed and execution continues as described in this context.
</p>
<p>If <code>swapcontext</code> succeeds the function does not return unless the
context <var>oucp</var> is used without prior modification by
<code>makecontext</code>. The return value in this case is <code>0</code>. If the
function fails it returns <code>-1</code> and set <var>errno</var> accordingly.
</p></dd></dl>
<a name="Example-for-SVID-Context-Handling"></a>
<h2 class="heading">Example for SVID Context Handling</h2>
<p>The easiest way to use the context handling functions is as a
replacement for <code>setjmp</code> and <code>longjmp</code>. 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).
</p>
<table><tr><td> </td><td><pre class="smallexample">int
random_search (int n, int (*fp) (int, ucontext_t *))
{
volatile int cnt = 0;
ucontext_t uc;
/* <span class="roman">Safe current context.</span> */
if (getcontext (&uc) < 0)
return -1;
/* <span class="roman">If we have not tried <var>n</var> times try again.</span> */
if (cnt++ < n)
/* <span class="roman">Call the function with a new random number</span>
<span class="roman">and the context</span>. */
if (fp (rand (), &uc) != 0)
/* <span class="roman">We found what we were looking for.</span> */
return 1;
/* <span class="roman">Not found.</span> */
return 0;
}
</pre></td></tr></table>
<p>Using contexts in such a way enables emulating exception handling. The
search functions passed in the <var>fp</var> 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.
</p>
<p>Something which is harder to implement with <code>setjmp</code> and
<code>longjmp</code> is to switch temporarily to a different execution path
and then resume where execution was stopped.
</p>
<table><tr><td> </td><td><pre class="smallexample">#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
#include <sys/time.h>
/* <span class="roman">Set by the signal handler.</span> */
static volatile int expired;
/* <span class="roman">The contexts.</span> */
static ucontext_t uc[3];
/* <span class="roman">We do only a certain number of switches.</span> */
static int switches;
/* <span class="roman">This is the function doing the work. It is just a
skeleton, real code has to be filled in.</span> */
static void
f (int n)
{
int m = 0;
while (1)
{
/* <span class="roman">This is where the work would be done.</span> */
if (++m % 100 == 0)
{
putchar ('.');
fflush (stdout);
}
/* <span class="roman">Regularly the <var>expire</var> variable must be checked.</span> */
if (expired)
{
/* <span class="roman">We do not want the program to run forever.</span> */
if (++switches == 20)
return;
printf ("\nswitching from %d to %d\n", n, 3 - n);
expired = 0;
/* <span class="roman">Switch to the other context, saving the current one.</span> */
swapcontext (&uc[n], &uc[3 - n]);
}
}
}
/* <span class="roman">This is the signal handler which simply set the variable.</span> */
void
handler (int signal)
{
expired = 1;
}
int
main (void)
{
struct sigaction sa;
struct itimerval it;
char st1[8192];
char st2[8192];
/* <span class="roman">Initialize the data structures for the interval timer.</span> */
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;
/* <span class="roman">Install the timer and get the context we can manipulate.</span> */
if (sigaction (SIGPROF, &sa, NULL) < 0
|| setitimer (ITIMER_PROF, &it, NULL) < 0
|| getcontext (&uc[1]) == -1
|| getcontext (&uc[2]) == -1)
abort ();
/* <span class="roman">Create a context with a separate stack which causes the
function <code>f</code> to be call with the parameter <code>1</code>.
Note that the <code>uc_link</code> points to the main context
which will cause the program to terminate once the function
return.</span> */
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);
/* <span class="roman">Similarly, but <code>2</code> is passed as the parameter to <code>f</code>.</span> */
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);
/* <span class="roman">Start running.</span> */
swapcontext (&uc[0], &uc[1]);
putchar ('\n');
return 0;
}
</pre></td></tr></table>
<p>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 <code>swapcontext</code> to continue running a
different context. It is not allowed to do the context switching from
the signal handler directly since neither <code>setcontext</code> nor
<code>swapcontext</code> 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
<code>swapcontext</code> 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.
</p><hr size="6">
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="#Non_002dLocal-Exits" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="libc_24.html#Signal-Handling" title="Next chapter"> >> </a>]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="libc.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="libc_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="libc_42.html#Concept-Index" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="libc_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<p>
<font size="-1">
This document was generated by <em>root</em> on <em>April 20, 2012</em> using <a href="http://www.nongnu.org/texi2html/"><em>texi2html 1.82</em></a>.
</font>
<br>
</p>
</body>
</html>
|