1This is guile.info, produced by makeinfo version 6.7 from guile.texi.
2
3This manual documents Guile version 3.0.7.
4
5   Copyright (C) 1996-1997, 2000-2005, 2009-2021 Free Software
6Foundation, Inc.
7
8   Permission is granted to copy, distribute and/or modify this document
9under the terms of the GNU Free Documentation License, Version 1.3 or
10any later version published by the Free Software Foundation; with no
11Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
12copy of the license is included in the section entitled “GNU Free
13Documentation License.”
14INFO-DIR-SECTION The Algorithmic Language Scheme
15START-INFO-DIR-ENTRY
16* Guile Reference: (guile).     The Guile reference manual.
17END-INFO-DIR-ENTRY
18
19
20File: guile.info,  Node: Scheduling,  Next: Options and Config,  Prev: Smobs,  Up: API Reference
21
226.22 Threads, Mutexes, Asyncs and Dynamic Roots
23===============================================
24
25* Menu:
26
27* Threads::                     Multiple threads of execution.
28* Thread Local Variables::      Some fluids are thread-local.
29* Asyncs::                      Asynchronous interrupts.
30* Atomics::                     Atomic references.
31* Mutexes and Condition Variables:: Synchronization primitives.
32* Blocking::                    How to block properly in guile mode.
33* Futures::                     Fine-grain parallelism.
34* Parallel Forms::              Parallel execution of forms.
35
36
37File: guile.info,  Node: Threads,  Next: Thread Local Variables,  Up: Scheduling
38
396.22.1 Threads
40--------------
41
42Guile supports POSIX threads, unless it was configured with
43‘--without-threads’ or the host lacks POSIX thread support.  When thread
44support is available, the ‘threads’ feature is provided (*note
45‘provided?’: Feature Manipulation.).
46
47   The procedures below manipulate Guile threads, which are wrappers
48around the system’s POSIX threads.  For application-level parallelism,
49using higher-level constructs, such as futures, is recommended (*note
50Futures::).
51
52   To use these facilities, load the ‘(ice-9 threads)’ module.
53
54     (use-modules (ice-9 threads))
55
56 -- Scheme Procedure: all-threads
57 -- C Function: scm_all_threads ()
58     Return a list of all threads.
59
60 -- Scheme Procedure: current-thread
61 -- C Function: scm_current_thread ()
62     Return the thread that called this function.
63
64 -- Scheme Procedure: call-with-new-thread thunk [handler]
65     Call ‘thunk’ in a new thread and with a new dynamic state,
66     returning the new thread.  The procedure THUNK is called via
67     ‘with-continuation-barrier’.
68
69     When HANDLER is specified, then THUNK is called from within a
70     ‘catch’ with tag ‘#t’ that has HANDLER as its handler.  This catch
71     is established inside the continuation barrier.
72
73     Once THUNK or HANDLER returns, the return value is made the _exit
74     value_ of the thread and the thread is terminated.
75
76 -- C Function: SCM scm_spawn_thread (scm_t_catch_body body, void
77          *body_data, scm_t_catch_handler handler, void *handler_data)
78     Call BODY in a new thread, passing it BODY_DATA, returning the new
79     thread.  The function BODY is called via
80     ‘scm_c_with_continuation_barrier’.
81
82     When HANDLER is non-‘NULL’, BODY is called via ‘scm_internal_catch’
83     with tag ‘SCM_BOOL_T’ that has HANDLER and HANDLER_DATA as the
84     handler and its data.  This catch is established inside the
85     continuation barrier.
86
87     Once BODY or HANDLER returns, the return value is made the _exit
88     value_ of the thread and the thread is terminated.
89
90 -- Scheme Procedure: thread? obj
91 -- C Function: scm_thread_p (obj)
92     Return ‘#t’ ff OBJ is a thread; otherwise, return ‘#f’.
93
94 -- Scheme Procedure: join-thread thread [timeout [timeoutval]]
95 -- C Function: scm_join_thread (thread)
96 -- C Function: scm_join_thread_timed (thread, timeout, timeoutval)
97     Wait for THREAD to terminate and return its exit value.  Only
98     threads that were created with ‘call-with-new-thread’ or
99     ‘scm_spawn_thread’ can be joinable; attempting to join a foreign
100     thread will raise an error.
101
102     When TIMEOUT is given, it specifies a point in time where the
103     waiting should be aborted.  It can be either an integer as returned
104     by ‘current-time’ or a pair as returned by ‘gettimeofday’.  When
105     the waiting is aborted, TIMEOUTVAL is returned (if it is specified;
106     ‘#f’ is returned otherwise).
107
108 -- Scheme Procedure: thread-exited? thread
109 -- C Function: scm_thread_exited_p (thread)
110     Return ‘#t’ if THREAD has exited, or ‘#f’ otherwise.
111
112 -- Scheme Procedure: yield
113 -- C Function: scm_yield (thread)
114     If one or more threads are waiting to execute, calling yield forces
115     an immediate context switch to one of them.  Otherwise, yield has
116     no effect.
117
118 -- Scheme Procedure: cancel-thread thread . values
119 -- C Function: scm_cancel_thread (thread)
120     Asynchronously interrupt THREAD and ask it to terminate.
121     ‘dynamic-wind’ post thunks will run, but throw handlers will not.
122     If THREAD has already terminated or been signaled to terminate,
123     this function is a no-op.  Calling ‘join-thread’ on the thread will
124     return the given VALUES, if the cancel succeeded.
125
126     Under the hood, thread cancellation uses ‘system-async-mark’ and
127     ‘abort-to-prompt’.  *Note Asyncs:: for more on asynchronous
128     interrupts.
129
130 -- macro: make-thread proc arg ...
131     Apply PROC to ARG ... in a new thread formed by
132     ‘call-with-new-thread’ using a default error handler that displays
133     the error to the current error port.  The ARG ... expressions are
134     evaluated in the new thread.
135
136 -- macro: begin-thread expr1 expr2 ...
137     Evaluate forms EXPR1 EXPR2 ... in a new thread formed by
138     ‘call-with-new-thread’ using a default error handler that displays
139     the error to the current error port.
140
141   One often wants to limit the number of threads running to be
142proportional to the number of available processors.  These interfaces
143are therefore exported by (ice-9 threads) as well.
144
145 -- Scheme Procedure: total-processor-count
146 -- C Function: scm_total_processor_count ()
147     Return the total number of processors of the machine, which is
148     guaranteed to be at least 1.  A “processor” here is a thread
149     execution unit, which can be either:
150
151        • an execution core in a (possibly multi-core) chip, in a
152          (possibly multi- chip) module, in a single computer, or
153        • a thread execution unit inside a core in the case of
154          “hyper-threaded” CPUs.
155
156     Which of the two definitions is used, is unspecified.
157
158 -- Scheme Procedure: current-processor-count
159 -- C Function: scm_current_processor_count ()
160     Like ‘total-processor-count’, but return the number of processors
161     available to the current process.  See ‘setaffinity’ and
162     ‘getaffinity’ for more information.
163
164
165File: guile.info,  Node: Thread Local Variables,  Next: Asyncs,  Prev: Threads,  Up: Scheduling
166
1676.22.2 Thread-Local Variables
168-----------------------------
169
170Sometimes you want to establish a variable binding that is only valid
171for a given thread: a “thread-local variable”.
172
173   You would think that fluids or parameters would be Guile’s answer for
174thread-local variables, since establishing a new fluid binding doesn’t
175affect bindings in other threads.  *Note Fluids and Dynamic States::, or
176*Note Parameters::.  However, new threads inherit the fluid bindings
177that were in place in their creator threads.  In this way, a binding
178established using a fluid (or a parameter) in a thread can escape to
179other threads, which might not be what you want.  Or, it might escape
180via explicit reification via ‘current-dynamic-state’.
181
182   Of course, this dynamic scoping might be exactly what you want;
183that’s why fluids and parameters work this way, and is what you want for
184for many common parameters such as the current input and output ports,
185the current locale conversion parameters, and the like.  Perhaps this is
186the case for most parameters, even.  If your use case for thread-local
187bindings comes from a desire to isolate a binding from its setting in
188unrelated threads, then fluids and parameters apply nicely.
189
190   On the other hand, if your use case is to prevent concurrent access
191to a value from multiple threads, then using vanilla fluids or
192parameters is not appropriate.  For this purpose, Guile has
193“thread-local fluids”.  A fluid created with ‘make-thread-local-fluid’
194won’t be captured by ‘current-dynamic-state’ and won’t be propagated to
195new threads.
196
197 -- Scheme Procedure: make-thread-local-fluid [dflt]
198 -- C Function: scm_make_thread_local_fluid (dflt)
199     Return a newly created fluid, whose initial value is DFLT, or ‘#f’
200     if DFLT is not given.  Unlike fluids made with ‘make-fluid’, thread
201     local fluids are not captured by ‘make-dynamic-state’.  Similarly,
202     a newly spawned child thread does not inherit thread-local fluid
203     values from the parent thread.
204
205 -- Scheme Procedure: fluid-thread-local? fluid
206 -- C Function: scm_fluid_thread_local_p (fluid)
207     Return ‘#t’ if the fluid FLUID is is thread-local, or ‘#f’
208     otherwise.
209
210   For example:
211
212     (define %thread-local (make-thread-local-fluid))
213
214     (with-fluids ((%thread-local (compute-data)))
215       ... (fluid-ref %thread-local) ...)
216
217   You can also make a thread-local parameter out of a thread-local
218fluid using the normal ‘fluid->parameter’:
219
220     (define param (fluid->parameter (make-thread-local-fluid)))
221
222     (parameterize ((param (compute-data)))
223       ... (param) ...)
224
225
226File: guile.info,  Node: Asyncs,  Next: Atomics,  Prev: Thread Local Variables,  Up: Scheduling
227
2286.22.3 Asynchronous Interrupts
229------------------------------
230
231Every Guile thread can be interrupted.  Threads running Guile code will
232periodically check if there are pending interrupts and run them if
233necessary.  To interrupt a thread, call ‘system-async-mark’ on that
234thread.
235
236 -- Scheme Procedure: system-async-mark proc [thread]
237 -- C Function: scm_system_async_mark (proc)
238 -- C Function: scm_system_async_mark_for_thread (proc, thread)
239     Enqueue PROC (a procedure with zero arguments) for future execution
240     in THREAD.  When PROC has already been enqueued for THREAD but has
241     not been executed yet, this call has no effect.  When THREAD is
242     omitted, the thread that called ‘system-async-mark’ is used.
243
244   Note that ‘scm_system_async_mark_for_thread’ is not
245“async-signal-safe” and so cannot be called from a C signal handler.
246(Indeed in general, ‘libguile’ functions are not safe to call from C
247signal handlers.)
248
249   Though an interrupt procedure can have any side effect permitted to
250Guile code, asynchronous interrupts are generally used either for
251profiling or for prematurely cancelling a computation.  The former case
252is mostly transparent to the program being run, by design, but the
253latter case can introduce bugs.  Like finalizers (*note Foreign Object
254Memory Management::), asynchronous interrupts introduce concurrency in a
255program.  An asyncronous interrupt can run in the middle of some
256mutex-protected operation, for example, and potentially corrupt the
257program’s state.
258
259   If some bit of Guile code needs to temporarily inhibit interrupts, it
260can use ‘call-with-blocked-asyncs’.  This function works by temporarily
261increasing the _async blocking level_ of the current thread while a
262given procedure is running.  The blocking level starts out at zero, and
263whenever a safe point is reached, a blocking level greater than zero
264will prevent the execution of queued asyncs.
265
266   Analogously, the procedure ‘call-with-unblocked-asyncs’ will
267temporarily decrease the blocking level of the current thread.  You can
268use it when you want to disable asyncs by default and only allow them
269temporarily.
270
271   In addition to the C versions of ‘call-with-blocked-asyncs’ and
272‘call-with-unblocked-asyncs’, C code can use ‘scm_dynwind_block_asyncs’
273and ‘scm_dynwind_unblock_asyncs’ inside a “dynamic context” (*note
274Dynamic Wind::) to block or unblock asyncs temporarily.
275
276 -- Scheme Procedure: call-with-blocked-asyncs proc
277 -- C Function: scm_call_with_blocked_asyncs (proc)
278     Call PROC and block the execution of asyncs by one level for the
279     current thread while it is running.  Return the value returned by
280     PROC.  For the first two variants, call PROC with no arguments; for
281     the third, call it with DATA.
282
283 -- C Function: void * scm_c_call_with_blocked_asyncs (void * (*proc)
284          (void *data), void *data)
285     The same but with a C function PROC instead of a Scheme thunk.
286
287 -- Scheme Procedure: call-with-unblocked-asyncs proc
288 -- C Function: scm_call_with_unblocked_asyncs (proc)
289     Call PROC and unblock the execution of asyncs by one level for the
290     current thread while it is running.  Return the value returned by
291     PROC.  For the first two variants, call PROC with no arguments; for
292     the third, call it with DATA.
293
294 -- C Function: void * scm_c_call_with_unblocked_asyncs (void *(*proc)
295          (void *data), void *data)
296     The same but with a C function PROC instead of a Scheme thunk.
297
298 -- C Function: void scm_dynwind_block_asyncs ()
299     During the current dynwind context, increase the blocking of asyncs
300     by one level.  This function must be used inside a pair of calls to
301     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
302
303 -- C Function: void scm_dynwind_unblock_asyncs ()
304     During the current dynwind context, decrease the blocking of asyncs
305     by one level.  This function must be used inside a pair of calls to
306     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
307
308   Sometimes you want to interrupt a thread that might be waiting for
309something to happen, for example on a file descriptor or a condition
310variable.  In that case you can inform Guile of how to interrupt that
311wait using the following procedures:
312
313 -- C Function: int scm_c_prepare_to_wait_on_fd (int fd)
314     Inform Guile that the current thread is about to sleep, and that if
315     an asynchronous interrupt is signalled on this thread, Guile should
316     wake up the thread by writing a zero byte to FD.  Returns zero if
317     the prepare succeeded, or nonzero if the thread already has a
318     pending async and that it should avoid waiting.
319
320 -- C Function: int scm_c_prepare_to_wait_on_cond (scm_i_pthread_mutex_t
321          *mutex, scm_i_pthread_cond_t *cond)
322     Inform Guile that the current thread is about to sleep, and that if
323     an asynchronous interrupt is signalled on this thread, Guile should
324     wake up the thread by acquiring MUTEX and signalling COND.  The
325     caller must already hold MUTEX and only drop it as part of the
326     ‘pthread_cond_wait’ call.  Returns zero if the prepare succeeded,
327     or nonzero if the thread already has a pending async and that it
328     should avoid waiting.
329
330 -- C Function: void scm_c_wait_finished (void)
331     Inform Guile that the current thread has finished waiting, and that
332     asynchronous interrupts no longer need any special wakeup action;
333     the current thread will periodically poll its internal queue
334     instead.
335
336   Guile’s own interface to ‘sleep’, ‘wait-condition-variable’,
337‘select’, and so on all call the above routines as appropriate.
338
339   Finally, note that threads can also be interrupted via POSIX signals.
340*Note Signals::.  As an implementation detail, signal handlers will
341effectively call ‘system-async-mark’ in a signal-safe way, eventually
342running the signal handler using the same async mechanism.  In this way
343you can temporarily inhibit signal handlers from running using the above
344interfaces.
345
346
347File: guile.info,  Node: Atomics,  Next: Mutexes and Condition Variables,  Prev: Asyncs,  Up: Scheduling
348
3496.22.4 Atomics
350--------------
351
352When accessing data in parallel from multiple threads, updates made by
353one thread are not generally guaranteed to be visible by another thread.
354It could be that your hardware requires special instructions to be
355emitted to propagate a change from one CPU core to another.  Or, it
356could be that your hardware updates values with a sequence of
357instructions, and a parallel thread could see a value that is in the
358process of being updated but not fully updated.
359
360   Atomic references solve this problem.  Atomics are a standard,
361primitive facility to allow for concurrent access and update of mutable
362variables from multiple threads with guaranteed forward-progress and
363well-defined intermediate states.
364
365   Atomic references serve not only as a hardware memory barrier but
366also as a compiler barrier.  Normally a compiler might choose to reorder
367or elide certain memory accesses due to optimizations like common
368subexpression elimination.  Atomic accesses however will not be
369reordered relative to each other, and normal memory accesses will not be
370reordered across atomic accesses.
371
372   As an implementation detail, currently all atomic accesses and
373updates use the sequential consistency memory model from C11.  We may
374relax this in the future to the acquire/release semantics, which still
375issues a memory barrier so that non-atomic updates are not reordered
376across atomic accesses or updates.
377
378   To use Guile’s atomic operations, load the ‘(ice-9 atomic)’ module:
379
380     (use-modules (ice-9 atomic))
381
382 -- Scheme Procedure: make-atomic-box init
383     Return an atomic box initialized to value INIT.
384
385 -- Scheme Procedure: atomic-box? obj
386     Return ‘#t’ if OBJ is an atomic-box object, else return ‘#f’.
387
388 -- Scheme Procedure: atomic-box-ref box
389     Fetch the value stored in the atomic box BOX and return it.
390
391 -- Scheme Procedure: atomic-box-set! box val
392     Store VAL into the atomic box BOX.
393
394 -- Scheme Procedure: atomic-box-swap! box val
395     Store VAL into the atomic box BOX, and return the value that was
396     previously stored in the box.
397
398 -- Scheme Procedure: atomic-box-compare-and-swap! box expected desired
399     If the value of the atomic box BOX is the same as, EXPECTED (in the
400     sense of ‘eq?’), replace the contents of the box with DESIRED.
401     Otherwise does not update the box.  Returns the previous value of
402     the box in either case, so you can know if the swap worked by
403     checking if the return value is ‘eq?’ to EXPECTED.
404
405
406File: guile.info,  Node: Mutexes and Condition Variables,  Next: Blocking,  Prev: Atomics,  Up: Scheduling
407
4086.22.5 Mutexes and Condition Variables
409--------------------------------------
410
411Mutexes are low-level primitives used to coordinate concurrent access to
412mutable data.  Short for “mutual exclusion”, the name “mutex” indicates
413that only one thread at a time can acquire access to data that is
414protected by a mutex – threads are excluded from accessing data at the
415same time.  If one thread has locked a mutex, then another thread
416attempting to lock that same mutex will wait until the first thread is
417done.
418
419   Mutexes can be used to build robust multi-threaded programs that take
420advantage of multiple cores.  However, they provide very low-level
421functionality and are somewhat dangerous; usually you end up wanting to
422acquire multiple mutexes at the same time to perform a multi-object
423access, but this can easily lead to deadlocks if the program is not
424carefully written.  For example, if objects A and B are protected by
425associated mutexes M and N, respectively, then to access both of them
426then you need to acquire both mutexes.  But what if one thread acquires
427M first and then N, at the same time that another thread acquires N them
428M? You can easily end up in a situation where one is waiting for the
429other.
430
431   There’s no easy way around this problem on the language level.  A
432function A that uses mutexes does not necessarily compose nicely with a
433function B that uses mutexes.  For this reason we suggest using atomic
434variables when you can (*note Atomics::), as they do not have this
435problem.
436
437   Still, if you as a programmer are responsible for a whole system,
438then you can use mutexes as a primitive to provide safe concurrent
439abstractions to your users.  (For example, given all locks in a system,
440if you establish an order such that M is consistently acquired before N,
441you can avoid the “deadly-embrace” deadlock described above.  The
442problem is enumerating all mutexes and establishing this order from a
443system perspective.)  Guile gives you the low-level facilities to build
444such systems.
445
446   In Guile there are additional considerations beyond the usual ones in
447other programming languages: non-local control flow and asynchronous
448interrupts.  What happens if you hold a mutex, but somehow you cause an
449exception to be thrown?  There is no one right answer.  You might want
450to keep the mutex locked to prevent any other code from ever entering
451that critical section again.  Or, your critical section might be fine if
452you unlock the mutex “on the way out”, via an exception handler or
453‘dynamic-wind’.  *Note Exceptions::, and *Note Dynamic Wind::.
454
455   But if you arrange to unlock the mutex when leaving a dynamic extent
456via ‘dynamic-wind’, what to do if control re-enters that dynamic extent
457via a continuation invocation?  Surely re-entering the dynamic extent
458without the lock is a bad idea, so there are two options on the table:
459either prevent re-entry via ‘with-continuation-barrier’ or similar, or
460reacquire the lock in the entry thunk of a ‘dynamic-wind’.
461
462   You might think that because you don’t use continuations, that you
463don’t have to think about this, and you might be right.  If you control
464the whole system, you can reason about continuation use globally.  Or,
465if you know all code that can be called in a dynamic extent, and none of
466that code can call continuations, then you don’t have to worry about
467re-entry, and you might not have to worry about early exit either.
468
469   However, do consider the possibility of asynchronous interrupts
470(*note Asyncs::).  If the user interrupts your code interactively, that
471can cause an exception; or your thread might be cancelled, which does
472the same; or the user could be running your code under some pre-emptive
473system that periodically causes lightweight task switching.  (Guile does
474not currently include such a system, but it’s possible to implement as a
475library.)  Probably you also want to defer asynchronous interrupt
476processing while you hold the mutex, and probably that also means that
477you should not hold the mutex for very long.
478
479   All of these additional Guile-specific considerations mean that from
480a system perspective, you would do well to avoid these hazards if you
481can by not requiring mutexes.  Instead, work with immutable data that
482can be shared between threads without hazards, or use persistent data
483structures with atomic updates based on the atomic variable library
484(*note Atomics::).
485
486   There are three types of mutexes in Guile: “standard”, “recursive”,
487and “unowned”.
488
489   Calling ‘make-mutex’ with no arguments makes a standard mutex.  A
490standard mutex can only be locked once.  If you try to lock it again
491from the thread that locked it to begin with (the "owner" thread), it
492throws an error.  It can only be unlocked from the thread that locked it
493in the first place.
494
495   Calling ‘make-mutex’ with the symbol ‘recursive’ as the argument, or
496calling ‘make-recursive-mutex’, will give you a recursive mutex.  A
497recursive mutex can be locked multiple times by its owner.  It then has
498to be unlocked the corresponding number of times, and like standard
499mutexes can only be unlocked by the owner thread.
500
501   Finally, calling ‘make-mutex’ with the symbol ‘allow-external-unlock’
502creates an unowned mutex.  An unowned mutex is like a standard mutex,
503except that it can be unlocked by any thread.  A corollary of this
504behavior is that a thread’s attempt to lock a mutex that it already owns
505will block instead of signalling an error, as it could be that some
506other thread unlocks the mutex, allowing the owner thread to proceed.
507This kind of mutex is a bit strange and is here for use by SRFI-18.
508
509   The mutex procedures in Guile can operate on all three kinds of
510mutexes.
511
512   To use these facilities, load the ‘(ice-9 threads)’ module.
513
514     (use-modules (ice-9 threads))
515
516
517 -- Scheme Procedure: make-mutex [kind]
518 -- C Function: scm_make_mutex ()
519 -- C Function: scm_make_mutex_with_kind (SCM kind)
520     Return a new mutex.  It will be a standard non-recursive mutex,
521     unless the ‘recursive’ symbol is passed as the optional KIND
522     argument, in which case it will be recursive.  It’s also possible
523     to pass ‘unowned’ for semantics tailored to SRFI-18’s use case; see
524     above for details.
525
526 -- Scheme Procedure: mutex? obj
527 -- C Function: scm_mutex_p (obj)
528     Return ‘#t’ if OBJ is a mutex; otherwise, return ‘#f’.
529
530 -- Scheme Procedure: make-recursive-mutex
531 -- C Function: scm_make_recursive_mutex ()
532     Create a new recursive mutex.  It is initially unlocked.  Calling
533     this function is equivalent to calling ‘make-mutex’ with the
534     ‘recursive’ kind.
535
536 -- Scheme Procedure: lock-mutex mutex [timeout]
537 -- C Function: scm_lock_mutex (mutex)
538 -- C Function: scm_timed_lock_mutex (mutex, timeout)
539     Lock MUTEX and return ‘#t’.  If the mutex is already locked, then
540     block and return only when MUTEX has been acquired.
541
542     When TIMEOUT is given, it specifies a point in time where the
543     waiting should be aborted.  It can be either an integer as returned
544     by ‘current-time’ or a pair as returned by ‘gettimeofday’.  When
545     the waiting is aborted, ‘#f’ is returned.
546
547     For standard mutexes (‘make-mutex’), an error is signalled if the
548     thread has itself already locked MUTEX.
549
550     For a recursive mutex (‘make-recursive-mutex’), if the thread has
551     itself already locked MUTEX, then a further ‘lock-mutex’ call
552     increments the lock count.  An additional ‘unlock-mutex’ will be
553     required to finally release.
554
555     When an asynchronous interrupt (*note Asyncs::) is scheduled for a
556     thread blocked in ‘lock-mutex’, Guile will interrupt the wait, run
557     the interrupts, and then resume the wait.
558
559 -- C Function: void scm_dynwind_lock_mutex (SCM mutex)
560     Arrange for MUTEX to be locked whenever the current dynwind context
561     is entered and to be unlocked when it is exited.
562
563 -- Scheme Procedure: try-mutex mx
564 -- C Function: scm_try_mutex (mx)
565     Try to lock MUTEX and return ‘#t’ if successful, or ‘#f’ otherwise.
566     This is like calling ‘lock-mutex’ with an expired timeout.
567
568 -- Scheme Procedure: unlock-mutex mutex
569 -- C Function: scm_unlock_mutex (mutex)
570     Unlock MUTEX.  An error is signalled if MUTEX is not locked.
571
572     “Standard” and “recursive” mutexes can only be unlocked by the
573     thread that locked them; Guile detects this situation and signals
574     an error.  “Unowned” mutexes can be unlocked by any thread.
575
576 -- Scheme Procedure: mutex-owner mutex
577 -- C Function: scm_mutex_owner (mutex)
578     Return the current owner of MUTEX, in the form of a thread or ‘#f’
579     (indicating no owner).  Note that a mutex may be unowned but still
580     locked.
581
582 -- Scheme Procedure: mutex-level mutex
583 -- C Function: scm_mutex_level (mutex)
584     Return the current lock level of MUTEX.  If MUTEX is currently
585     unlocked, this value will be 0; otherwise, it will be the number of
586     times MUTEX has been recursively locked by its current owner.
587
588 -- Scheme Procedure: mutex-locked? mutex
589 -- C Function: scm_mutex_locked_p (mutex)
590     Return ‘#t’ if MUTEX is locked, regardless of ownership; otherwise,
591     return ‘#f’.
592
593 -- Scheme Procedure: make-condition-variable
594 -- C Function: scm_make_condition_variable ()
595     Return a new condition variable.
596
597 -- Scheme Procedure: condition-variable? obj
598 -- C Function: scm_condition_variable_p (obj)
599     Return ‘#t’ if OBJ is a condition variable; otherwise, return ‘#f’.
600
601 -- Scheme Procedure: wait-condition-variable condvar mutex [time]
602 -- C Function: scm_wait_condition_variable (condvar, mutex, time)
603     Wait until CONDVAR has been signalled.  While waiting, MUTEX is
604     atomically unlocked (as with ‘unlock-mutex’) and is locked again
605     when this function returns.  When TIME is given, it specifies a
606     point in time where the waiting should be aborted.  It can be
607     either a integer as returned by ‘current-time’ or a pair as
608     returned by ‘gettimeofday’.  When the waiting is aborted, ‘#f’ is
609     returned.  When the condition variable has in fact been signalled,
610     ‘#t’ is returned.  The mutex is re-locked in any case before
611     ‘wait-condition-variable’ returns.
612
613     When an async is activated for a thread that is blocked in a call
614     to ‘wait-condition-variable’, the waiting is interrupted, the mutex
615     is locked, and the async is executed.  When the async returns, the
616     mutex is unlocked again and the waiting is resumed.  When the
617     thread block while re-acquiring the mutex, execution of asyncs is
618     blocked.
619
620 -- Scheme Procedure: signal-condition-variable condvar
621 -- C Function: scm_signal_condition_variable (condvar)
622     Wake up one thread that is waiting for CONDVAR.
623
624 -- Scheme Procedure: broadcast-condition-variable condvar
625 -- C Function: scm_broadcast_condition_variable (condvar)
626     Wake up all threads that are waiting for CONDVAR.
627
628   Guile also includes some higher-level abstractions for working with
629mutexes.
630
631 -- macro: with-mutex mutex body1 body2 ...
632     Lock MUTEX, evaluate the body BODY1 BODY2 ..., then unlock MUTEX.
633     The return value is that returned by the last body form.
634
635     The lock, body and unlock form the branches of a ‘dynamic-wind’
636     (*note Dynamic Wind::), so MUTEX is automatically unlocked if an
637     error or new continuation exits the body, and is re-locked if the
638     body is re-entered by a captured continuation.
639
640 -- macro: monitor body1 body2 ...
641     Evaluate the body form BODY1 BODY2 ... with a mutex locked so only
642     one thread can execute that code at any one time.  The return value
643     is the return from the last body form.
644
645     Each ‘monitor’ form has its own private mutex and the locking and
646     evaluation is as per ‘with-mutex’ above.  A standard mutex
647     (‘make-mutex’) is used, which means the body must not recursively
648     re-enter the ‘monitor’ form.
649
650     The term “monitor” comes from operating system theory, where it
651     means a particular bit of code managing access to some resource and
652     which only ever executes on behalf of one process at any one time.
653
654
655File: guile.info,  Node: Blocking,  Next: Futures,  Prev: Mutexes and Condition Variables,  Up: Scheduling
656
6576.22.6 Blocking in Guile Mode
658-----------------------------
659
660Up to Guile version 1.8, a thread blocked in guile mode would prevent
661the garbage collector from running.  Thus threads had to explicitly
662leave guile mode with ‘scm_without_guile ()’ before making a potentially
663blocking call such as a mutex lock, a ‘select ()’ system call, etc.  The
664following functions could be used to temporarily leave guile mode or to
665perform some common blocking operations in a supported way.
666
667   Starting from Guile 2.0, blocked threads no longer hinder garbage
668collection.  Thus, the functions below are not needed anymore.  They can
669still be used to inform the GC that a thread is about to block, giving
670it a (small) optimization opportunity for “stop the world” garbage
671collections, should they occur while the thread is blocked.
672
673 -- C Function: void * scm_without_guile (void *(*func) (void *), void
674          *data)
675     Leave guile mode, call FUNC on DATA, enter guile mode and return
676     the result of calling FUNC.
677
678     While a thread has left guile mode, it must not call any libguile
679     functions except ‘scm_with_guile’ or ‘scm_without_guile’ and must
680     not use any libguile macros.  Also, local variables of type ‘SCM’
681     that are allocated while not in guile mode are not protected from
682     the garbage collector.
683
684     When used from non-guile mode, calling ‘scm_without_guile’ is still
685     allowed: it simply calls FUNC.  In that way, you can leave guile
686     mode without having to know whether the current thread is in guile
687     mode or not.
688
689 -- C Function: int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
690     Like ‘pthread_mutex_lock’, but leaves guile mode while waiting for
691     the mutex.
692
693 -- C Function: int scm_pthread_cond_wait (pthread_cond_t *cond,
694          pthread_mutex_t *mutex)
695 -- C Function: int scm_pthread_cond_timedwait (pthread_cond_t *cond,
696          pthread_mutex_t *mutex, struct timespec *abstime)
697     Like ‘pthread_cond_wait’ and ‘pthread_cond_timedwait’, but leaves
698     guile mode while waiting for the condition variable.
699
700 -- C Function: int scm_std_select (int nfds, fd_set *readfds, fd_set
701          *writefds, fd_set *exceptfds, struct timeval *timeout)
702     Like ‘select’ but leaves guile mode while waiting.  Also, the
703     delivery of an async causes this function to be interrupted with
704     error code ‘EINTR’.
705
706 -- C Function: unsigned int scm_std_sleep (unsigned int seconds)
707     Like ‘sleep’, but leaves guile mode while sleeping.  Also, the
708     delivery of an async causes this function to be interrupted.
709
710 -- C Function: unsigned long scm_std_usleep (unsigned long usecs)
711     Like ‘usleep’, but leaves guile mode while sleeping.  Also, the
712     delivery of an async causes this function to be interrupted.
713
714
715File: guile.info,  Node: Futures,  Next: Parallel Forms,  Prev: Blocking,  Up: Scheduling
716
7176.22.7 Futures
718--------------
719
720The ‘(ice-9 futures)’ module provides “futures”, a construct for
721fine-grain parallelism.  A future is a wrapper around an expression
722whose computation may occur in parallel with the code of the calling
723thread, and possibly in parallel with other futures.  Like promises,
724futures are essentially proxies that can be queried to obtain the value
725of the enclosed expression:
726
727     (touch (future (+ 2 3)))
728     ⇒ 5
729
730   However, unlike promises, the expression associated with a future may
731be evaluated on another CPU core, should one be available.  This
732supports “fine-grain parallelism”, because even relatively small
733computations can be embedded in futures.  Consider this sequential code:
734
735     (define (find-prime lst1 lst2)
736       (or (find prime? lst1)
737           (find prime? lst2)))
738
739   The two arms of ‘or’ are potentially computation-intensive.  They are
740independent of one another, yet, they are evaluated sequentially when
741the first one returns ‘#f’.  Using futures, one could rewrite it like
742this:
743
744     (define (find-prime lst1 lst2)
745       (let ((f (future (find prime? lst2))))
746         (or (find prime? lst1)
747             (touch f))))
748
749   This preserves the semantics of ‘find-prime’.  On a multi-core
750machine, though, the computation of ‘(find prime? lst2)’ may be done in
751parallel with that of the other ‘find’ call, which can reduce the
752execution time of ‘find-prime’.
753
754   Futures may be nested: a future can itself spawn and then ‘touch’
755other futures, leading to a directed acyclic graph of futures.  Using
756this facility, a parallel ‘map’ procedure can be defined along these
757lines:
758
759     (use-modules (ice-9 futures) (ice-9 match))
760
761     (define (par-map proc lst)
762       (match lst
763         (()
764          '())
765         ((head tail ...)
766          (let ((tail (future (par-map proc tail)))
767                (head (proc head)))
768            (cons head (touch tail))))))
769
770   Note that futures are intended for the evaluation of purely
771functional expressions.  Expressions that have side-effects or rely on
772I/O may require additional care, such as explicit synchronization (*note
773Mutexes and Condition Variables::).
774
775   Guile’s futures are implemented on top of POSIX threads (*note
776Threads::).  Internally, a fixed-size pool of threads is used to
777evaluate futures, such that offloading the evaluation of an expression
778to another thread doesn’t incur thread creation costs.  By default, the
779pool contains one thread per available CPU core, minus one, to account
780for the main thread.  The number of available CPU cores is determined
781using ‘current-processor-count’ (*note Processes::).
782
783   When a thread touches a future that has not completed yet, it
784processes any pending future while waiting for it to complete, or just
785waits if there are no pending futures.  When ‘touch’ is called from
786within a future, the execution of the calling future is suspended,
787allowing its host thread to process other futures, and resumed when the
788touched future has completed.  This suspend/resume is achieved by
789capturing the calling future’s continuation, and later reinstating it
790(*note delimited continuations: Prompts.).
791
792 -- Scheme Syntax: future exp
793     Return a future for expression EXP.  This is equivalent to:
794
795          (make-future (lambda () exp))
796
797 -- Scheme Procedure: make-future thunk
798     Return a future for THUNK, a zero-argument procedure.
799
800     This procedure returns immediately.  Execution of THUNK may begin
801     in parallel with the calling thread’s computations, if idle CPU
802     cores are available, or it may start when ‘touch’ is invoked on the
803     returned future.
804
805     If the execution of THUNK throws an exception, that exception will
806     be re-thrown when ‘touch’ is invoked on the returned future.
807
808 -- Scheme Procedure: future? obj
809     Return ‘#t’ if OBJ is a future.
810
811 -- Scheme Procedure: touch f
812     Return the result of the expression embedded in future F.
813
814     If the result was already computed in parallel, ‘touch’ returns
815     instantaneously.  Otherwise, it waits for the computation to
816     complete, if it already started, or initiates it.  In the former
817     case, the calling thread may process other futures in the meantime.
818
819
820File: guile.info,  Node: Parallel Forms,  Prev: Futures,  Up: Scheduling
821
8226.22.8 Parallel forms
823---------------------
824
825The functions described in this section are available from
826
827     (use-modules (ice-9 threads))
828
829   They provide high-level parallel constructs.  The following functions
830are implemented in terms of futures (*note Futures::).  Thus they are
831relatively cheap as they re-use existing threads, and portable, since
832they automatically use one thread per available CPU core.
833
834 -- syntax: parallel expr ...
835     Evaluate each EXPR expression in parallel, each in its own thread.
836     Return the results of N expressions as a set of N multiple values
837     (*note Multiple Values::).
838
839 -- syntax: letpar ((var expr) ...) body1 body2 ...
840     Evaluate each EXPR in parallel, each in its own thread, then bind
841     the results to the corresponding VAR variables, and then evaluate
842     BODY1 BODY2 ...
843
844     ‘letpar’ is like ‘let’ (*note Local Bindings::), but all the
845     expressions for the bindings are evaluated in parallel.
846
847 -- Scheme Procedure: par-map proc lst1 lst2 ...
848 -- Scheme Procedure: par-for-each proc lst1 lst2 ...
849     Call PROC on the elements of the given lists.  ‘par-map’ returns a
850     list comprising the return values from PROC.  ‘par-for-each’
851     returns an unspecified value, but waits for all calls to complete.
852
853     The PROC calls are ‘(PROC ELEM1 ELEM2 ...)’, where each ELEM is
854     from the corresponding LST .  Each LST must be the same length.
855     The calls are potentially made in parallel, depending on the number
856     of CPU cores available.
857
858     These functions are like ‘map’ and ‘for-each’ (*note List
859     Mapping::), but make their PROC calls in parallel.
860
861   Unlike those above, the functions described below take a number of
862threads as an argument.  This makes them inherently non-portable since
863the specified number of threads may differ from the number of available
864CPU cores as returned by ‘current-processor-count’ (*note Processes::).
865In addition, these functions create the specified number of threads when
866they are called and terminate them upon completion, which makes them
867quite expensive.
868
869   Therefore, they should be avoided.
870
871 -- Scheme Procedure: n-par-map n proc lst1 lst2 ...
872 -- Scheme Procedure: n-par-for-each n proc lst1 lst2 ...
873     Call PROC on the elements of the given lists, in the same way as
874     ‘par-map’ and ‘par-for-each’ above, but use no more than N threads
875     at any one time.  The order in which calls are initiated within
876     that threads limit is unspecified.
877
878     These functions are good for controlling resource consumption if
879     PROC calls might be costly, or if there are many to be made.  On a
880     dual-CPU system for instance N=4 might be enough to keep the CPUs
881     utilized, and not consume too much memory.
882
883 -- Scheme Procedure: n-for-each-par-map n sproc pproc lst1 lst2 ...
884     Apply PPROC to the elements of the given lists, and apply SPROC to
885     each result returned by PPROC.  The final return value is
886     unspecified, but all calls will have been completed before
887     returning.
888
889     The calls made are ‘(SPROC (PPROC ELEM1 ... ELEMN))’, where each
890     ELEM is from the corresponding LST.  Each LST must have the same
891     number of elements.
892
893     The PPROC calls are made in parallel, in separate threads.  No more
894     than N threads are used at any one time.  The order in which PPROC
895     calls are initiated within that limit is unspecified.
896
897     The SPROC calls are made serially, in list element order, one at a
898     time.  PPROC calls on later elements may execute in parallel with
899     the SPROC calls.  Exactly which thread makes each SPROC call is
900     unspecified.
901
902     This function is designed for individual calculations that can be
903     done in parallel, but with results needing to be handled serially,
904     for instance to write them to a file.  The N limit on threads
905     controls system resource usage when there are many calculations or
906     when they might be costly.
907
908     It will be seen that ‘n-for-each-par-map’ is like a combination of
909     ‘n-par-map’ and ‘for-each’,
910
911          (for-each sproc (n-par-map n pproc lst1 ... lstN))
912
913     But the actual implementation is more efficient since each SPROC
914     call, in turn, can be initiated once the relevant PPROC call has
915     completed, it doesn’t need to wait for all to finish.
916
917
918File: guile.info,  Node: Options and Config,  Next: Other Languages,  Prev: Scheduling,  Up: API Reference
919
9206.23 Configuration, Features and Runtime Options
921================================================
922
923Why is my Guile different from your Guile?  There are three kinds of
924possible variation:
925
926   • build differences — different versions of the Guile source code,
927     installation directories, configuration flags that control pieces
928     of functionality being included or left out, etc.
929
930   • differences in dynamically loaded code — behaviour and features
931     provided by modules that can be dynamically loaded into a running
932     Guile
933
934   • different runtime options — some of the options that are provided
935     for controlling Guile’s behaviour may be set differently.
936
937   Guile provides “introspective” variables and procedures to query all
938of these possible variations at runtime.  For runtime options, it also
939provides procedures to change the settings of options and to obtain
940documentation on what the options mean.
941
942* Menu:
943
944* Build Config::                Build and installation configuration.
945* Feature Tracking::            Available features in the Guile process.
946* Runtime Options::             Controlling Guile’s runtime behaviour.
947
948
949File: guile.info,  Node: Build Config,  Next: Feature Tracking,  Up: Options and Config
950
9516.23.1 Configuration, Build and Installation
952--------------------------------------------
953
954The following procedures and variables provide information about how
955Guile was configured, built and installed on your system.
956
957 -- Scheme Procedure: version
958 -- Scheme Procedure: effective-version
959 -- Scheme Procedure: major-version
960 -- Scheme Procedure: minor-version
961 -- Scheme Procedure: micro-version
962 -- C Function: scm_version ()
963 -- C Function: scm_effective_version ()
964 -- C Function: scm_major_version ()
965 -- C Function: scm_minor_version ()
966 -- C Function: scm_micro_version ()
967     Return a string describing Guile’s full version number, effective
968     version number, major, minor or micro version number, respectively.
969     The ‘effective-version’ function returns the version name that
970     should remain unchanged during a stable series.  Currently that
971     means that it omits the micro version.  The effective version
972     should be used for items like the versioned share directory name
973     i.e./usr/share/guile/3.0/’
974
975          (version) ⇒ "3.0.0"
976          (effective-version) ⇒ "3.0"
977          (major-version) ⇒ "3"
978          (minor-version) ⇒ "0"
979          (micro-version) ⇒ "0"
980
981 -- Scheme Procedure: %package-data-dir
982 -- C Function: scm_sys_package_data_dir ()
983     Return the name of the directory under which Guile Scheme files in
984     general are stored.  On Unix-like systems, this is usually
985/usr/local/share/guile’ or ‘/usr/share/guile’.
986
987 -- Scheme Procedure: %library-dir
988 -- C Function: scm_sys_library_dir ()
989     Return the name of the directory where the Guile Scheme files that
990     belong to the core Guile installation (as opposed to files from a
991     3rd party package) are installed.  On Unix-like systems this is
992     usually ‘/usr/local/share/guile/GUILE_EFFECTIVE_VERSION’ or
993/usr/share/guile/GUILE_EFFECTIVE_VERSION’;
994
995     for example ‘/usr/local/share/guile/3.0’.
996
997 -- Scheme Procedure: %site-dir
998 -- C Function: scm_sys_site_dir ()
999     Return the name of the directory where Guile Scheme files specific
1000     to your site should be installed.  On Unix-like systems, this is
1001     usually ‘/usr/local/share/guile/site’ or ‘/usr/share/guile/site’.
1002
1003 -- Scheme Procedure: %site-ccache-dir
1004 -- C Function: scm_sys_site_ccache_dir ()
1005     Return the directory where users should install compiled ‘.go’
1006     files for use with this version of Guile.  Might look something
1007     like ‘/usr/lib/guile/3.0/site-ccache’.
1008
1009 -- Variable: %guile-build-info
1010     Alist of information collected during the building of a particular
1011     Guile.  Entries can be grouped into one of several categories:
1012     directories, env vars, and versioning info.
1013
1014     Briefly, here are the keys in ‘%guile-build-info’, by group:
1015
1016     directories
1017          srcdir, top_srcdir, prefix, exec_prefix, bindir, sbindir,
1018          libexecdir, datadir, sysconfdir, sharedstatedir,
1019          localstatedir, libdir, infodir, mandir, includedir,
1020          pkgdatadir, pkglibdir, pkgincludedir
1021     env vars
1022          LIBS
1023     versioning info
1024          guileversion, libguileinterface, buildstamp
1025
1026     Values are all strings.  The value for ‘LIBS’ is typically found
1027     also as a part of ‘pkg-config --libs guile-3.0’ output.  The value
1028     for ‘guileversion’ has form X.Y.Z, and should be the same as
1029     returned by ‘(version)’.  The value for ‘libguileinterface’ is
1030     libtool compatible and has form CURRENT:REVISION:AGE (*note Library
1031     interface versions: (libtool)Versioning.).  The value for
1032     ‘buildstamp’ is the output of the command ‘date -u +'%Y-%m-%d %T'’
1033     (UTC).
1034
1035     In the source, ‘%guile-build-info’ is initialized from
1036     libguile/libpath.h, which is completely generated, so deleting this
1037     file before a build guarantees up-to-date values for that build.
1038
1039 -- Variable: %host-type
1040     The canonical host type (GNU triplet) of the host Guile was
1041     configured for, e.g., ‘"x86_64-unknown-linux-gnu"’ (*note
1042     (autoconf)Canonicalizing::).
1043
1044
1045File: guile.info,  Node: Feature Tracking,  Next: Runtime Options,  Prev: Build Config,  Up: Options and Config
1046
10476.23.2 Feature Tracking
1048-----------------------
1049
1050Guile has a Scheme level variable ‘*features*’ that keeps track to some
1051extent of the features that are available in a running Guile.
1052‘*features*’ is a list of symbols, for example ‘threads’, each of which
1053describes a feature of the running Guile process.
1054
1055 -- Variable: *features*
1056     A list of symbols describing available features of the Guile
1057     process.
1058
1059   You shouldn’t modify the ‘*features*’ variable directly using ‘set!’.
1060Instead, see the procedures that are provided for this purpose in the
1061following subsection.
1062
1063* Menu:
1064
1065* Feature Manipulation::        Checking for and advertising features.
1066* Common Feature Symbols::      Commonly available features.
1067
1068
1069File: guile.info,  Node: Feature Manipulation,  Next: Common Feature Symbols,  Up: Feature Tracking
1070
10716.23.2.1 Feature Manipulation
1072.............................
1073
1074To check whether a particular feature is available, use the ‘provided?’
1075procedure:
1076
1077 -- Scheme Procedure: provided? feature
1078 -- Deprecated Scheme Procedure: feature? feature
1079     Return ‘#t’ if the specified FEATURE is available, otherwise ‘#f’.
1080
1081   To advertise a feature from your own Scheme code, you can use the
1082‘provide’ procedure:
1083
1084 -- Scheme Procedure: provide feature
1085     Add FEATURE to the list of available features in this Guile
1086     process.
1087
1088   For C code, the equivalent function takes its feature name as a ‘char
1089*’ argument for convenience:
1090
1091 -- C Function: void scm_add_feature (const char *str)
1092     Add a symbol with name STR to the list of available features in
1093     this Guile process.
1094
1095
1096File: guile.info,  Node: Common Feature Symbols,  Prev: Feature Manipulation,  Up: Feature Tracking
1097
10986.23.2.2 Common Feature Symbols
1099...............................
1100
1101In general, a particular feature may be available for one of two
1102reasons.  Either because the Guile library was configured and compiled
1103with that feature enabled — i.e. the feature is built into the library
1104on your system.  Or because some C or Scheme code that was dynamically
1105loaded by Guile has added that feature to the list.
1106
1107   In the first category, here are the features that the current version
1108of Guile may define (depending on how it is built), and what they mean.
1109
1110‘array’
1111     Indicates support for arrays (*note Arrays::).
1112
1113‘array-for-each’
1114     Indicates availability of ‘array-for-each’ and other array mapping
1115     procedures (*note Arrays::).
1116
1117‘char-ready?’
1118     Indicates that the ‘char-ready?’ function is available (*note
1119     Venerable Port Interfaces::).
1120
1121‘complex’
1122     Indicates support for complex numbers.
1123
1124‘current-time’
1125     Indicates availability of time-related functions: ‘times’,
1126     ‘get-internal-run-time’ and so on (*note Time::).
1127
1128‘debug-extensions’
1129     Indicates that the debugging evaluator is available, together with
1130     the options for controlling it.
1131
1132‘delay’
1133     Indicates support for promises (*note Delayed Evaluation::).
1134
1135‘EIDs’
1136     Indicates that the ‘geteuid’ and ‘getegid’ really return effective
1137     user and group IDs (*note Processes::).
1138
1139‘inexact’
1140     Indicates support for inexact numbers.
1141
1142i/o-extensions1143     Indicates availability of the following extended I/O procedures:
1144     ‘ftell’, ‘redirect-port’, ‘dup->fdes’, ‘dup2’, ‘fileno’, ‘isatty?’,
1145     ‘fdopen’, ‘primitive-move->fdes’ and ‘fdes->ports’ (*note Ports and
1146     File Descriptors::).
1147
1148‘net-db’
1149     Indicates availability of network database functions:
1150     ‘scm_gethost’, ‘scm_getnet’, ‘scm_getproto’, ‘scm_getserv’,
1151     ‘scm_sethost’, ‘scm_setnet’, ‘scm_setproto’, ‘scm_setserv’, and
1152     their ‘byXXX’ variants (*note Network Databases::).
1153
1154‘posix’
1155     Indicates support for POSIX functions: ‘pipe’, ‘getgroups’, ‘kill’,
1156     ‘execl’ and so on (*note POSIX::).
1157
1158‘fork’
1159     Indicates support for the POSIX ‘fork’ function (*note
1160     ‘primitive-fork’: Processes.).
1161
1162‘popen’
1163     Indicates support for ‘open-pipe’ in the ‘(ice-9 popen)’ module
1164     (*note Pipes::).
1165
1166‘random’
1167     Indicates availability of random number generation functions:
1168     ‘random’, ‘copy-random-state’, ‘random-uniform’ and so on (*note
1169     Random::).
1170
1171‘reckless’
1172     Indicates that Guile was built with important checks omitted — you
1173     should never see this!
1174
1175‘regex’
1176     Indicates support for POSIX regular expressions using
1177     ‘make-regexp’, ‘regexp-exec’ and friends (*note Regexp
1178     Functions::).
1179
1180‘socket’
1181     Indicates availability of socket-related functions: ‘socket’,
1182     ‘bind’, ‘connect’ and so on (*note Network Sockets and
1183     Communication::).
1184
1185‘sort’
1186     Indicates availability of sorting and merging functions (*note
1187     Sorting::).
1188
1189‘system’
1190     Indicates that the ‘system’ function is available (*note
1191     Processes::).
1192
1193‘threads’
1194     Indicates support for multithreading (*note Threads::).
1195
1196‘values’
1197     Indicates support for multiple return values using ‘values’ and
1198     ‘call-with-values’ (*note Multiple Values::).
1199
1200   Available features in the second category depend, by definition, on
1201what additional code your Guile process has loaded in.  The following
1202table lists features that you might encounter for this reason.
1203
1204‘defmacro’
1205     Indicates that the ‘defmacro’ macro is available (*note Macros::).
1206
1207‘describe’
1208     Indicates that the ‘(oop goops describe)’ module has been loaded,
1209     which provides a procedure for describing the contents of GOOPS
1210     instances.
1211
1212‘readline’
1213     Indicates that Guile has loaded in Readline support, for command
1214     line editing (*note Readline Support::).
1215
1216‘record’
1217     Indicates support for record definition using ‘make-record-type’
1218     and friends (*note Records::).
1219
1220   Although these tables may seem exhaustive, it is probably unwise in
1221practice to rely on them, as the correspondences between feature symbols
1222and available procedures/behaviour are not strictly defined.  If you are
1223writing code that needs to check for the existence of some procedure, it
1224is probably safer to do so directly using the ‘defined?’ procedure than
1225to test for the corresponding feature using ‘provided?’.
1226
1227
1228File: guile.info,  Node: Runtime Options,  Prev: Feature Tracking,  Up: Options and Config
1229
12306.23.3 Runtime Options
1231----------------------
1232
1233There are a number of runtime options available for paramaterizing
1234built-in procedures, like ‘read’, and built-in behavior, like what
1235happens on an uncaught error.
1236
1237   For more information on reader options, *Note Scheme Read::.
1238
1239   For more information on print options, *Note Scheme Write::.
1240
1241   Finally, for more information on debugger options, *Note Debug
1242Options::.
1243
12446.23.3.1 Examples of option use
1245...............................
1246
1247Here is an example of a session in which some read and debug option
1248handling procedures are used.  In this example, the user
1249
1250  1. Notices that the symbols ‘abc’ and ‘aBc’ are not the same
1251  2. Examines the ‘read-options’, and sees that ‘case-insensitive’ is
1252     set to “no”.
1253  3. Enables ‘case-insensitive’
1254  4. Quits the recursive prompt
1255  5. Verifies that now ‘aBc’ and ‘abc’ are the same
1256
1257     scheme@(guile-user)> (define abc "hello")
1258     scheme@(guile-user)> abc
1259     $1 = "hello"
1260     scheme@(guile-user)> aBc
1261     <unknown-location>: warning: possibly unbound variable `aBc'
1262     ERROR: In procedure module-lookup:
1263     ERROR: Unbound variable: aBc
1264     Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.
1265     scheme@(guile-user) [1]> (read-options 'help)
1266     copy              no    Copy source code expressions.
1267     positions         yes   Record positions of source code expressions.
1268     case-insensitive  no    Convert symbols to lower case.
1269     keywords          #f    Style of keyword recognition: #f, 'prefix or 'postfix.
1270     r6rs-hex-escapes  no    Use R6RS variable-length character and string hex escapes.
1271     square-brackets   yes   Treat `[' and `]' as parentheses, for R6RS compatibility.
1272     hungry-eol-escapes no   In strings, consume leading whitespace after an
1273                             escaped end-of-line.
1274     curly-infix       no    Support SRFI-105 curly infix expressions.
1275     scheme@(guile-user) [1]> (read-enable 'case-insensitive)
1276     $2 = (square-brackets keywords #f case-insensitive positions)
1277     scheme@(guile-user) [1]> ,q
1278     scheme@(guile-user)> aBc
1279     $3 = "hello"
1280
1281
1282File: guile.info,  Node: Other Languages,  Next: Internationalization,  Prev: Options and Config,  Up: API Reference
1283
12846.24 Support for Other Languages
1285================================
1286
1287In addition to Scheme, a user may write a Guile program in an increasing
1288number of other languages.  Currently supported languages include Emacs
1289Lisp and ECMAScript.
1290
1291   Guile is still fundamentally a Scheme, but it tries to support a wide
1292variety of language building-blocks, so that other languages can be
1293implemented on top of Guile.  This allows users to write or extend
1294applications in languages other than Scheme, too.  This section
1295describes the languages that have been implemented.
1296
1297   (For details on how to implement a language, *Note Compiling to the
1298Virtual Machine::.)
1299
1300* Menu:
1301
1302* Using Other Languages::       How to use other languages.
1303* Emacs Lisp::                  The dialect of Lisp used in Emacs.
1304* ECMAScript::                  As seen on television.
1305
1306
1307File: guile.info,  Node: Using Other Languages,  Next: Emacs Lisp,  Up: Other Languages
1308
13096.24.1 Using Other Languages
1310----------------------------
1311
1312There are currently only two ways to access other languages from within
1313Guile: at the REPL, and programmatically, via ‘compile’,
1314‘read-and-compile’, and ‘compile-file’.
1315
1316   The REPL is Guile’s command prompt (*note Using Guile
1317Interactively::).  The REPL has a concept of the “current language”,
1318which defaults to Scheme.  The user may change that language, via the
1319meta-command ‘,language’.
1320
1321   For example, the following meta-command enables Emacs Lisp input:
1322
1323     scheme@(guile-user)> ,language elisp
1324     Happy hacking with Emacs Lisp!  To switch back, type `,L scheme'.
1325     elisp@(guile-user)> (eq 1 2)
1326     $1 = #nil
1327
1328   Each language has its short name: for example, ‘elisp’, for Elisp.
1329The same short name may be used to compile source code programmatically,
1330via ‘compile’:
1331
1332     elisp@(guile-user)> ,L scheme
1333     Happy hacking with Guile Scheme!  To switch back, type `,L elisp'.
1334     scheme@(guile-user)> (compile '(eq 1 2) #:from 'elisp)
1335     $2 = #nil
1336
1337   Granted, as the input to ‘compile’ is a datum, this works best for
1338Lispy languages, which have a straightforward datum representation.
1339Other languages that need more parsing are better dealt with as strings.
1340
1341   The easiest way to deal with syntax-heavy language is with files, via
1342‘compile-file’ and friends.  However it is possible to invoke a
1343language’s reader on a port, and then compile the resulting expression
1344(which is a datum at that point).  For more information, *Note
1345Compilation::.
1346
1347   For more details on introspecting aspects of different languages,
1348*Note Compiler Tower::.
1349
1350
1351File: guile.info,  Node: Emacs Lisp,  Next: ECMAScript,  Prev: Using Other Languages,  Up: Other Languages
1352
13536.24.2 Emacs Lisp
1354-----------------
1355
1356Emacs Lisp (Elisp) is a dynamically-scoped Lisp dialect used in the
1357Emacs editor.  *Note Overview: (elisp)top, for more information on Emacs
1358Lisp.
1359
1360   We hope that eventually Guile’s implementation of Elisp will be good
1361enough to replace Emacs’ own implementation of Elisp.  For that reason,
1362we have thought long and hard about how to support the various features
1363of Elisp in a performant and compatible manner.
1364
1365   Readers familiar with Emacs Lisp might be curious about how exactly
1366these various Elisp features are supported in Guile.  The rest of this
1367section focuses on addressing these concerns of the Elisp elect.
1368
1369* Menu:
1370
1371* Nil::                         A third boolean.
1372* Dynamic Binding::             Threadsafe bindings with fluids.
1373* Other Elisp Features::        Miscellany.
1374
1375
1376File: guile.info,  Node: Nil,  Next: Dynamic Binding,  Up: Emacs Lisp
1377
13786.24.2.1 Nil
1379............
1380
1381‘nil’ in ELisp is an amalgam of Scheme’s ‘#f’ and ‘'()’.  It is false,
1382and it is the end-of-list; thus it is a boolean, and a list as well.
1383
1384   Guile has chosen to support ‘nil’ as a separate value, distinct from
1385‘#f’ and ‘'()’.  This allows existing Scheme and Elisp code to maintain
1386their current semantics.  ‘nil’, which in Elisp would just be written
1387and read as ‘nil’, in Scheme has the external representation ‘#nil’.
1388
1389   In Elisp code, ‘#nil’, ‘#f’, and ‘'()’ behave like ‘nil’, in the
1390sense that they are all interpreted as ‘nil’ by Elisp ‘if’, ‘cond’,
1391‘when’, ‘not’, ‘null’, etc.  To test whether Elisp would interpret an
1392object as ‘nil’ from within Scheme code, use ‘nil?’:
1393
1394 -- Scheme Procedure: nil? obj
1395     Return ‘#t’ if OBJ would be interpreted as ‘nil’ by Emacs Lisp
1396     code, else return ‘#f’.
1397
1398          (nil? #nil) ⇒ #t
1399          (nil? #f)   ⇒ #t
1400          (nil? '())  ⇒ #t
1401          (nil? 3)    ⇒ #f
1402
1403   This decision to have ‘nil’ as a low-level distinct value facilitates
1404interoperability between the two languages.  Guile has chosen to have
1405Scheme deal with ‘nil’ as follows:
1406
1407     (boolean? #nil) ⇒ #t
1408     (not #nil) ⇒ #t
1409     (null? #nil) ⇒ #t
1410
1411   And in C, one has:
1412
1413     scm_is_bool (SCM_ELISP_NIL) ⇒ 1
1414     scm_is_false (SCM_ELISP_NIL) ⇒ 1
1415     scm_is_null (SCM_ELISP_NIL) ⇒ 1
1416
1417   In this way, a version of ‘fold’ written in Scheme can correctly fold
1418a function written in Elisp (or in fact any other language) over a
1419nil-terminated list, as Elisp makes.  The converse holds as well; a
1420version of ‘fold’ written in Elisp can fold over a ‘'()’-terminated
1421list, as made by Scheme.
1422
1423   On a low level, the bit representations for ‘#f’, ‘#t’, ‘nil’, and
1424‘'()’ are made in such a way that they differ by only one bit, and so a
1425test for, for example, ‘#f’-or-‘nil’ may be made very efficiently.  See
1426libguile/boolean.h’, for more information.
1427
1428Equality
1429........
1430
1431Since Scheme’s ‘equal?’ must be transitive, and ‘'()’ is not ‘equal?’ to
1432‘#f’, to Scheme ‘nil’ is not ‘equal?’ to ‘#f’ or ‘'()’.
1433
1434     (eq? #f '()) ⇒ #f
1435     (eq? #nil '()) ⇒ #f
1436     (eq? #nil #f) ⇒ #f
1437     (eqv? #f '()) ⇒ #f
1438     (eqv? #nil '()) ⇒ #f
1439     (eqv? #nil #f) ⇒ #f
1440     (equal? #f '()) ⇒ #f
1441     (equal? #nil '()) ⇒ #f
1442     (equal? #nil #f) ⇒ #f
1443
1444   However, in Elisp, ‘'()’, ‘#f’, and ‘nil’ are all ‘equal’ (though not
1445‘eq’).
1446
1447     (defvar f (make-scheme-false))
1448     (defvar eol (make-scheme-null))
1449     (eq f eol) ⇒ nil
1450     (eq nil eol) ⇒ nil
1451     (eq nil f) ⇒ nil
1452     (equal f eol) ⇒ t
1453     (equal nil eol) ⇒ t
1454     (equal nil f) ⇒ t
1455
1456   These choices facilitate interoperability between Elisp and Scheme
1457code, but they are not perfect.  Some code that is correct standard
1458Scheme is not correct in the presence of a second false and null value.
1459For example:
1460
1461     (define (truthiness x)
1462       (if (eq? x #f)
1463           #f
1464           #t))
1465
1466   This code seems to be meant to test a value for truth, but now that
1467there are two false values, ‘#f’ and ‘nil’, it is no longer correct.
1468
1469   Similarly, there is the loop:
1470
1471     (define (my-length l)
1472       (let lp ((l l) (len 0))
1473         (if (eq? l '())
1474             len
1475             (lp (cdr l) (1+ len)))))
1476
1477   Here, ‘my-length’ will raise an error if L is a ‘nil’-terminated
1478list.
1479
1480   Both of these examples are correct standard Scheme, but, depending on
1481what they really want to do, they are not correct Guile Scheme.
1482Correctly written, they would test the _properties_ of falsehood or
1483nullity, not the individual members of that set.  That is to say, they
1484should use ‘not’ or ‘null?’ to test for falsehood or nullity, not ‘eq?’
1485or ‘memv’ or the like.
1486
1487   Fortunately, using ‘not’ and ‘null?’ is in good style, so all
1488well-written standard Scheme programs are correct, in Guile Scheme.
1489
1490   Here are correct versions of the above examples:
1491
1492     (define (truthiness* x)
1493       (if (not x)
1494           #f
1495           #t))
1496     ;; or: (define (t* x) (not (not x)))
1497     ;; or: (define (t** x) x)
1498
1499     (define (my-length* l)
1500       (let lp ((l l) (len 0))
1501         (if (null? l)
1502             len
1503             (lp (cdr l) (1+ len)))))
1504
1505   This problem has a mirror-image case in Elisp:
1506
1507     (defun my-falsep (x)
1508       (if (eq x nil)
1509           t
1510           nil))
1511
1512   Guile can warn when compiling code that has equality comparisons with
1513‘#f’, ‘'()’, or ‘nil’.  *Note Compilation::, for details.
1514
1515
1516File: guile.info,  Node: Dynamic Binding,  Next: Other Elisp Features,  Prev: Nil,  Up: Emacs Lisp
1517
15186.24.2.2 Dynamic Binding
1519........................
1520
1521In contrast to Scheme, which uses “lexical scoping”, Emacs Lisp scopes
1522its variables dynamically.  Guile supports dynamic scoping with its
1523“fluids” facility.  *Note Fluids and Dynamic States::, for more
1524information.
1525
1526
1527File: guile.info,  Node: Other Elisp Features,  Prev: Dynamic Binding,  Up: Emacs Lisp
1528
15296.24.2.3 Other Elisp Features
1530.............................
1531
1532Buffer-local and mode-local variables should be mentioned here, along
1533with buckybits on characters, Emacs primitive data types, the
1534Lisp-2-ness of Elisp, and other things.  Contributions to the
1535documentation are most welcome!
1536
1537
1538File: guile.info,  Node: ECMAScript,  Prev: Emacs Lisp,  Up: Other Languages
1539
15406.24.3 ECMAScript
1541-----------------
1542
1543ECMAScript
1544(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)
1545was not the first non-Schemey language implemented by Guile, but it was
1546the first implemented for Guile’s bytecode compiler.  The goal was to
1547support ECMAScript version 3.1, a relatively small language, but the
1548implementor was completely irresponsible and got distracted by other
1549things before finishing the standard library, and even some bits of the
1550syntax.  So, ECMAScript does deserve a mention in the manual, but it
1551doesn’t deserve an endorsement until its implementation is completed,
1552perhaps by some more responsible hacker.
1553
1554   In the meantime, the charitable user might investigate such
1555invocations as ‘,L ecmascript’ and ‘cat
1556test-suite/tests/ecmascript.test’.
1557
1558
1559File: guile.info,  Node: Internationalization,  Next: Debugging,  Prev: Other Languages,  Up: API Reference
1560
15616.25 Support for Internationalization
1562=====================================
1563
1564Guile provides internationalization(1) support for Scheme programs in
1565two ways.  First, procedures to manipulate text and data in a way that
1566conforms to particular cultural conventions (i.e., in a
1567“locale-dependent” way) are provided in the ‘(ice-9 i18n)’.  Second,
1568Guile allows the use of GNU ‘gettext’ to translate program message
1569strings.
1570
1571* Menu:
1572
1573* i18n Introduction::             Introduction to Guile’s i18n support.
1574* Text Collation::                Sorting strings and characters.
1575* Character Case Mapping::        Case mapping.
1576* Number Input and Output::       Parsing and printing numbers.
1577* Accessing Locale Information::  Detailed locale information.
1578* Gettext Support::               Translating message strings.
1579
1580   ---------- Footnotes ----------
1581
1582   (1) For concision and style, programmers often like to refer to
1583internationalization as “i18n”.
1584
1585
1586File: guile.info,  Node: i18n Introduction,  Next: Text Collation,  Prev: Internationalization,  Up: Internationalization
1587
15886.25.1 Internationalization with Guile
1589--------------------------------------
1590
1591In order to make use of the functions described thereafter, the ‘(ice-9
1592i18n)’ module must be imported in the usual way:
1593
1594     (use-modules (ice-9 i18n))
1595
1596   The ‘(ice-9 i18n)’ module provides procedures to manipulate text and
1597other data in a way that conforms to the cultural conventions chosen by
1598the user.  Each region of the world or language has its own customs to,
1599for instance, represent real numbers, classify characters, collate text,
1600etc.  All these aspects comprise the so-called “cultural conventions” of
1601that region or language.
1602
1603   Computer systems typically refer to a set of cultural conventions as
1604a “locale”.  For each particular aspect that comprise those cultural
1605conventions, a “locale category” is defined.  For instance, the way
1606characters are classified is defined by the ‘LC_CTYPE’ category, while
1607the language in which program messages are issued to the user is defined
1608by the ‘LC_MESSAGES’ category (*note General Locale Information:
1609Locales. for details).
1610
1611   The procedures provided by this module allow the development of
1612programs that adapt automatically to any locale setting.  As we will see
1613later, many of these procedures can optionally take a “locale object”
1614argument.  This additional argument defines the locale settings that
1615must be followed by the invoked procedure.  When it is omitted, then the
1616current locale settings of the process are followed (*note ‘setlocale’:
1617Locales.).
1618
1619   The following procedures allow the manipulation of such locale
1620objects.
1621
1622 -- Scheme Procedure: make-locale category-list locale-name
1623          [base-locale]
1624 -- C Function: scm_make_locale (category_list, locale_name,
1625          base_locale)
1626     Return a reference to a data structure representing a set of locale
1627     datasets.  LOCALE-NAME should be a string denoting a particular
1628     locale (e.g., ‘"aa_DJ"’) and CATEGORY-LIST should be either a list
1629     of locale categories or a single category as used with ‘setlocale’
1630     (*note ‘setlocale’: Locales.).  Optionally, if ‘base-locale’ is
1631     passed, it should be a locale object denoting settings for
1632     categories not listed in CATEGORY-LIST.
1633
1634     The following invocation creates a locale object that combines the
1635     use of Swedish for messages and character classification with the
1636     default settings for the other categories (i.e., the settings of
1637     the default ‘C’ locale which usually represents conventions in use
1638     in the USA):
1639
1640          (make-locale (list LC_MESSAGES LC_CTYPE) "sv_SE")
1641
1642     The following example combines the use of Esperanto messages and
1643     conventions with monetary conventions from Croatia:
1644
1645          (make-locale LC_MONETARY "hr_HR"
1646                       (make-locale LC_ALL "eo_EO"))
1647
1648     A ‘system-error’ exception (*note Handling Errors::) is raised by
1649     ‘make-locale’ when LOCALE-NAME does not match any of the locales
1650     compiled on the system.  Note that on non-GNU systems, this error
1651     may be raised later, when the locale object is actually used.
1652
1653 -- Scheme Procedure: locale? obj
1654 -- C Function: scm_locale_p (obj)
1655     Return true if OBJ is a locale object.
1656
1657 -- Scheme Variable: %global-locale
1658 -- C Variable: scm_global_locale
1659     This variable is bound to a locale object denoting the current
1660     process locale as installed using ‘setlocale ()’ (*note Locales::).
1661     It may be used like any other locale object, including as a third
1662     argument to ‘make-locale’, for instance.
1663
1664
1665File: guile.info,  Node: Text Collation,  Next: Character Case Mapping,  Prev: i18n Introduction,  Up: Internationalization
1666
16676.25.2 Text Collation
1668---------------------
1669
1670The following procedures provide support for text collation, i.e.,
1671locale-dependent string and character sorting.
1672
1673 -- Scheme Procedure: string-locale<? s1 s2 [locale]
1674 -- C Function: scm_string_locale_lt (s1, s2, locale)
1675 -- Scheme Procedure: string-locale>? s1 s2 [locale]
1676 -- C Function: scm_string_locale_gt (s1, s2, locale)
1677 -- Scheme Procedure: string-locale-ci<? s1 s2 [locale]
1678 -- C Function: scm_string_locale_ci_lt (s1, s2, locale)
1679 -- Scheme Procedure: string-locale-ci>? s1 s2 [locale]
1680 -- C Function: scm_string_locale_ci_gt (s1, s2, locale)
1681     Compare strings S1 and S2 in a locale-dependent way.  If LOCALE is
1682     provided, it should be locale object (as returned by ‘make-locale’)
1683     and will be used to perform the comparison; otherwise, the current
1684     system locale is used.  For the ‘-ci’ variants, the comparison is
1685     made in a case-insensitive way.
1686
1687 -- Scheme Procedure: string-locale-ci=? s1 s2 [locale]
1688 -- C Function: scm_string_locale_ci_eq (s1, s2, locale)
1689     Compare strings S1 and S2 in a case-insensitive, and
1690     locale-dependent way.  If LOCALE is provided, it should be a locale
1691     object (as returned by ‘make-locale’) and will be used to perform
1692     the comparison; otherwise, the current system locale is used.
1693
1694 -- Scheme Procedure: char-locale<? c1 c2 [locale]
1695 -- C Function: scm_char_locale_lt (c1, c2, locale)
1696 -- Scheme Procedure: char-locale>? c1 c2 [locale]
1697 -- C Function: scm_char_locale_gt (c1, c2, locale)
1698 -- Scheme Procedure: char-locale-ci<? c1 c2 [locale]
1699 -- C Function: scm_char_locale_ci_lt (c1, c2, locale)
1700 -- Scheme Procedure: char-locale-ci>? c1 c2 [locale]
1701 -- C Function: scm_char_locale_ci_gt (c1, c2, locale)
1702     Compare characters C1 and C2 according to either LOCALE (a locale
1703     object as returned by ‘make-locale’) or the current locale.  For
1704     the ‘-ci’ variants, the comparison is made in a case-insensitive
1705     way.
1706
1707 -- Scheme Procedure: char-locale-ci=? c1 c2 [locale]
1708 -- C Function: scm_char_locale_ci_eq (c1, c2, locale)
1709     Return true if character C1 is equal to C2, in a case insensitive
1710     way according to LOCALE or to the current locale.
1711
1712
1713File: guile.info,  Node: Character Case Mapping,  Next: Number Input and Output,  Prev: Text Collation,  Up: Internationalization
1714
17156.25.3 Character Case Mapping
1716-----------------------------
1717
1718The procedures below provide support for “character case mapping”, i.e.,
1719to convert characters or strings to their upper-case or lower-case
1720equivalent.  Note that SRFI-13 provides procedures that look similar
1721(*note Alphabetic Case Mapping::).  However, the SRFI-13 procedures are
1722locale-independent.  Therefore, they do not take into account
1723specificities of the customs in use in a particular language or region
1724of the world.  For instance, while most languages using the Latin
1725alphabet map lower-case letter “i” to upper-case letter “I”, Turkish
1726maps lower-case “i” to “Latin capital letter I with dot above”.  The
1727following procedures allow programmers to provide idiomatic character
1728mapping.
1729
1730 -- Scheme Procedure: char-locale-downcase chr [locale]
1731 -- C Function: scm_char_locale_upcase (chr, locale)
1732     Return the lowercase character that corresponds to CHR according to
1733     either LOCALE or the current locale.
1734
1735 -- Scheme Procedure: char-locale-upcase chr [locale]
1736 -- C Function: scm_char_locale_downcase (chr, locale)
1737     Return the uppercase character that corresponds to CHR according to
1738     either LOCALE or the current locale.
1739
1740 -- Scheme Procedure: char-locale-titlecase chr [locale]
1741 -- C Function: scm_char_locale_titlecase (chr, locale)
1742     Return the titlecase character that corresponds to CHR according to
1743     either LOCALE or the current locale.
1744
1745 -- Scheme Procedure: string-locale-upcase str [locale]
1746 -- C Function: scm_string_locale_upcase (str, locale)
1747     Return a new string that is the uppercase version of STR according
1748     to either LOCALE or the current locale.
1749
1750 -- Scheme Procedure: string-locale-downcase str [locale]
1751 -- C Function: scm_string_locale_downcase (str, locale)
1752     Return a new string that is the down-case version of STR according
1753     to either LOCALE or the current locale.
1754
1755 -- Scheme Procedure: string-locale-titlecase str [locale]
1756 -- C Function: scm_string_locale_titlecase (str, locale)
1757     Return a new string that is the titlecase version of STR according
1758     to either LOCALE or the current locale.
1759
1760
1761File: guile.info,  Node: Number Input and Output,  Next: Accessing Locale Information,  Prev: Character Case Mapping,  Up: Internationalization
1762
17636.25.4 Number Input and Output
1764------------------------------
1765
1766The following procedures allow programs to read and write numbers
1767written according to a particular locale.  As an example, in English,
1768“ten thousand and a half” is usually written ‘10,000.5’ while in French
1769it is written ‘10 000,5’.  These procedures allow such differences to be
1770taken into account.
1771
1772 -- Scheme Procedure: locale-string->integer str [base [locale]]
1773 -- C Function: scm_locale_string_to_integer (str, base, locale)
1774     Convert string STR into an integer according to either LOCALE (a
1775     locale object as returned by ‘make-locale’) or the current process
1776     locale.  If BASE is specified, then it determines the base of the
1777     integer being read (e.g., ‘16’ for an hexadecimal number, ‘10’ for
1778     a decimal number); by default, decimal numbers are read.  Return
1779     two values (*note Multiple Values::): an integer (on success) or
1780     ‘#f’, and the number of characters read from STR (‘0’ on failure).
1781
1782     This function is based on the C library’s ‘strtol’ function (*note
1783     ‘strtol’: (libc)Parsing of Integers.).
1784
1785 -- Scheme Procedure: locale-string->inexact str [locale]
1786 -- C Function: scm_locale_string_to_inexact (str, locale)
1787     Convert string STR into an inexact number according to either
1788     LOCALE (a locale object as returned by ‘make-locale’) or the
1789     current process locale.  Return two values (*note Multiple
1790     Values::): an inexact number (on success) or ‘#f’, and the number
1791     of characters read from STR (‘0’ on failure).
1792
1793     This function is based on the C library’s ‘strtod’ function (*note
1794     ‘strtod’: (libc)Parsing of Floats.).
1795
1796 -- Scheme Procedure: number->locale-string number [fraction-digits
1797          [locale]]
1798     Convert NUMBER (an inexact) into a string according to the cultural
1799     conventions of either LOCALE (a locale object) or the current
1800     locale.  By default, print as many fractional digits as necessary,
1801     up to an upper bound.  Optionally, FRACTION-DIGITS may be bound to
1802     an integer specifying the number of fractional digits to be
1803     displayed.
1804
1805 -- Scheme Procedure: monetary-amount->locale-string amount intl?
1806          [locale]
1807     Convert AMOUNT (an inexact denoting a monetary amount) into a
1808     string according to the cultural conventions of either LOCALE (a
1809     locale object) or the current locale.  If INTL? is true, then the
1810     international monetary format for the given locale is used (*note
1811     international and locale monetary formats: (libc)Currency Symbol.).
1812
1813
1814File: guile.info,  Node: Accessing Locale Information,  Next: Gettext Support,  Prev: Number Input and Output,  Up: Internationalization
1815
18166.25.5 Accessing Locale Information
1817-----------------------------------
1818
1819It is sometimes useful to obtain very specific information about a
1820locale such as the word it uses for days or months, its format for
1821representing floating-point figures, etc.  The ‘(ice-9 i18n)’ module
1822provides support for this in a way that is similar to the libc functions
1823‘nl_langinfo ()’ and ‘localeconv ()’ (*note accessing locale information
1824from C: (libc)Locale Information.).  The available functions are listed
1825below.
1826
1827 -- Scheme Procedure: locale-encoding [locale]
1828     Return the name of the encoding (a string whose interpretation is
1829     system-dependent) of either LOCALE or the current locale.
1830
1831   The following functions deal with dates and times.
1832
1833 -- Scheme Procedure: locale-day day [locale]
1834 -- Scheme Procedure: locale-day-short day [locale]
1835 -- Scheme Procedure: locale-month month [locale]
1836 -- Scheme Procedure: locale-month-short month [locale]
1837     Return the word (a string) used in either LOCALE or the current
1838     locale to name the day (or month) denoted by DAY (or MONTH), an
1839     integer between 1 and 7 (or 1 and 12).  The ‘-short’ variants
1840     provide an abbreviation instead of a full name.
1841
1842 -- Scheme Procedure: locale-am-string [locale]
1843 -- Scheme Procedure: locale-pm-string [locale]
1844     Return a (potentially empty) string that is used to denote ante
1845     meridiem (or post meridiem) hours in 12-hour format.
1846
1847 -- Scheme Procedure: locale-date+time-format [locale]
1848 -- Scheme Procedure: locale-date-format [locale]
1849 -- Scheme Procedure: locale-time-format [locale]
1850 -- Scheme Procedure: locale-time+am/pm-format [locale]
1851 -- Scheme Procedure: locale-era-date-format [locale]
1852 -- Scheme Procedure: locale-era-date+time-format [locale]
1853 -- Scheme Procedure: locale-era-time-format [locale]
1854     These procedures return format strings suitable to ‘strftime’
1855     (*note Time::) that may be used to display (part of) a date/time
1856     according to certain constraints and to the conventions of either
1857     LOCALE or the current locale (*note the ‘nl_langinfo ()’ items:
1858     (libc)The Elegant and Fast Way.).
1859
1860 -- Scheme Procedure: locale-era [locale]
1861 -- Scheme Procedure: locale-era-year [locale]
1862     These functions return, respectively, the era and the year of the
1863     relevant era used in LOCALE or the current locale.  Most locales do
1864     not define this value.  In this case, the empty string is returned.
1865     An example of a locale that does define this value is the Japanese
1866     one.
1867
1868   The following procedures give information about number
1869representation.
1870
1871 -- Scheme Procedure: locale-decimal-point [locale]
1872 -- Scheme Procedure: locale-thousands-separator [locale]
1873     These functions return a string denoting the representation of the
1874     decimal point or that of the thousand separator (respectively) for
1875     either LOCALE or the current locale.
1876
1877 -- Scheme Procedure: locale-digit-grouping [locale]
1878     Return a (potentially circular) list of integers denoting how
1879     digits of the integer part of a number are to be grouped, starting
1880     at the decimal point and going to the left.  The list contains
1881     integers indicating the size of the successive groups, from right
1882     to left.  If the list is non-circular, then no grouping occurs for
1883     digits beyond the last group.
1884
1885     For instance, if the returned list is a circular list that contains
1886     only ‘3’ and the thousand separator is ‘","’ (as is the case with
1887     English locales), then the number ‘12345678’ should be printed
1888     ‘12,345,678’.
1889
1890   The following procedures deal with the representation of monetary
1891amounts.  Some of them take an additional INTL? argument (a boolean)
1892that tells whether the international or local monetary conventions for
1893the given locale are to be used.
1894
1895 -- Scheme Procedure: locale-monetary-decimal-point [locale]
1896 -- Scheme Procedure: locale-monetary-thousands-separator [locale]
1897 -- Scheme Procedure: locale-monetary-grouping [locale]
1898     These are the monetary counterparts of the above procedures.  These
1899     procedures apply to monetary amounts.
1900
1901 -- Scheme Procedure: locale-currency-symbol intl? [locale]
1902     Return the currency symbol (a string) of either LOCALE or the
1903     current locale.
1904
1905     The following example illustrates the difference between the local
1906     and international monetary formats:
1907
1908          (define us (make-locale LC_MONETARY "en_US"))
1909          (locale-currency-symbol #f us)
1910          ⇒ "-$"
1911          (locale-currency-symbol #t us)
1912          ⇒ "USD "
1913
1914 -- Scheme Procedure: locale-monetary-fractional-digits intl? [locale]
1915     Return the number of fractional digits to be used when printing
1916     monetary amounts according to either LOCALE or the current locale.
1917     If the locale does not specify it, then ‘#f’ is returned.
1918
1919 -- Scheme Procedure: locale-currency-symbol-precedes-positive? intl?
1920          [locale]
1921 -- Scheme Procedure: locale-currency-symbol-precedes-negative? intl?
1922          [locale]
1923 -- Scheme Procedure: locale-positive-separated-by-space? intl? [locale]
1924 -- Scheme Procedure: locale-negative-separated-by-space? intl? [locale]
1925     These procedures return a boolean indicating whether the currency
1926     symbol should precede a positive/negative number, and whether a
1927     whitespace should be inserted between the currency symbol and a
1928     positive/negative amount.
1929
1930 -- Scheme Procedure: locale-monetary-positive-sign [locale]
1931 -- Scheme Procedure: locale-monetary-negative-sign [locale]
1932     Return a string denoting the positive (respectively negative) sign
1933     that should be used when printing a monetary amount.
1934
1935 -- Scheme Procedure: locale-positive-sign-position
1936 -- Scheme Procedure: locale-negative-sign-position
1937     These functions return a symbol telling where a sign of a
1938     positive/negative monetary amount is to appear when printing it.
1939     The possible values are:
1940
1941     ‘parenthesize’
1942          The currency symbol and quantity should be surrounded by
1943          parentheses.
1944     ‘sign-before’
1945          Print the sign string before the quantity and currency symbol.
1946     ‘sign-after’
1947          Print the sign string after the quantity and currency symbol.
1948     ‘sign-before-currency-symbol’
1949          Print the sign string right before the currency symbol.
1950     ‘sign-after-currency-symbol’
1951          Print the sign string right after the currency symbol.
1952     ‘unspecified’
1953          Unspecified.  We recommend you print the sign after the
1954          currency symbol.
1955
1956   Finally, the two following procedures may be helpful when programming
1957user interfaces:
1958
1959 -- Scheme Procedure: locale-yes-regexp [locale]
1960 -- Scheme Procedure: locale-no-regexp [locale]
1961     Return a string that can be used as a regular expression to
1962     recognize a positive (respectively, negative) response to a yes/no
1963     question.  For the C locale, the default values are typically
1964     ‘"^[yY]"’ and ‘"^[nN]"’, respectively.
1965
1966     Here is an example:
1967
1968          (use-modules (ice-9 rdelim))
1969          (format #t "Does Guile rock?~%")
1970          (let lp ((answer (read-line)))
1971            (cond ((string-match (locale-yes-regexp) answer)
1972                   (format #t "High fives!~%"))
1973                  ((string-match (locale-no-regexp) answer)
1974                   (format #t "How about now? Does it rock yet?~%")
1975                   (lp (read-line)))
1976                  (else
1977                   (format #t "What do you mean?~%")
1978                   (lp (read-line)))))
1979
1980     For an internationalized yes/no string output, ‘gettext’ should be
1981     used (*note Gettext Support::).
1982
1983   Example uses of some of these functions are the implementation of the
1984‘number->locale-string’ and ‘monetary-amount->locale-string’ procedures
1985(*note Number Input and Output::), as well as that the SRFI-19 date and
1986time conversion to/from strings (*note SRFI-19::).
1987
1988
1989File: guile.info,  Node: Gettext Support,  Prev: Accessing Locale Information,  Up: Internationalization
1990
19916.25.6 Gettext Support
1992----------------------
1993
1994Guile provides an interface to GNU ‘gettext’ for translating message
1995strings (*note (gettext)Introduction::).
1996
1997   Messages are collected in domains, so different libraries and
1998programs maintain different message catalogues.  The DOMAIN parameter in
1999the functions below is a string (it becomes part of the message catalog
2000filename).
2001
2002   When ‘gettext’ is not available, or if Guile was configured
2003‘--without-nls’, dummy functions doing no translation are provided.
2004When ‘gettext’ support is available in Guile, the ‘i18n’ feature is
2005provided (*note Feature Tracking::).
2006
2007 -- Scheme Procedure: gettext msg [domain [category]]
2008 -- C Function: scm_gettext (msg, domain, category)
2009     Return the translation of MSG in DOMAIN.  DOMAIN is optional and
2010     defaults to the domain set through ‘textdomain’ below.  CATEGORY is
2011     optional and defaults to ‘LC_MESSAGES’ (*note Locales::).
2012
2013     Normal usage is for MSG to be a literal string.  ‘xgettext’ can
2014     extract those from the source to form a message catalogue ready for
2015     translators (*note Invoking the ‘xgettext’ Program:
2016     (gettext)xgettext Invocation.).
2017
2018          (display (gettext "You are in a maze of twisty passages."))
2019
2020     It is conventional to use ‘G_’ as a shorthand for ‘gettext’.(1)
2021     Libraries can define ‘G_’ in such a way to look up translations
2022     using its specific DOMAIN, allowing different parts of a program to
2023     have different translation sources.
2024
2025          (define (G_ msg) (gettext msg "mylibrary"))
2026          (display (G_ "File not found."))
2027
2028     ‘G_’ is also a good place to perhaps strip disambiguating extra
2029     text from the message string, as for instance in *note How to use
2030     ‘gettext’ in GUI programs: (gettext)GUI program problems.
2031
2032 -- Scheme Procedure: ngettext msg msgplural n [domain [category]]
2033 -- C Function: scm_ngettext (msg, msgplural, n, domain, category)
2034     Return the translation of MSG/MSGPLURAL in DOMAIN, with a plural
2035     form chosen appropriately for the number N.  DOMAIN is optional and
2036     defaults to the domain set through ‘textdomain’ below.  CATEGORY is
2037     optional and defaults to ‘LC_MESSAGES’ (*note Locales::).
2038
2039     MSG is the singular form, and MSGPLURAL the plural.  When no
2040     translation is available, MSG is used if N = 1, or MSGPLURAL
2041     otherwise.  When translated, the message catalogue can have a
2042     different rule, and can have more than two possible forms.
2043
2044     As per ‘gettext’ above, normal usage is for MSG and MSGPLURAL to be
2045     literal strings, since ‘xgettext’ can extract them from the source
2046     to build a message catalogue.  For example,
2047
2048          (define (done n)
2049            (format #t (ngettext "~a file processed\n"
2050                                 "~a files processed\n" n)
2051                       n))
2052
2053          (done 1) ⊣ 1 file processed
2054          (done 3) ⊣ 3 files processed
2055
2056     It’s important to use ‘ngettext’ rather than plain ‘gettext’ for
2057     plurals, since the rules for singular and plural forms in English
2058     are not the same in other languages.  Only ‘ngettext’ will allow
2059     translators to give correct forms (*note Additional functions for
2060     plural forms: (gettext)Plural forms.).
2061
2062 -- Scheme Procedure: textdomain [domain]
2063 -- C Function: scm_textdomain (domain)
2064     Get or set the default gettext domain.  When called with no
2065     parameter the current domain is returned.  When called with a
2066     parameter, DOMAIN is set as the current domain, and that new value
2067     returned.  For example,
2068
2069          (textdomain "myprog")
2070          ⇒ "myprog"
2071
2072 -- Scheme Procedure: bindtextdomain domain [directory]
2073 -- C Function: scm_bindtextdomain (domain, directory)
2074     Get or set the directory under which to find message files for
2075     DOMAIN.  When called without a DIRECTORY the current setting is
2076     returned.  When called with a DIRECTORY, DIRECTORY is set for
2077     DOMAIN and that new setting returned.  For example,
2078
2079          (bindtextdomain "myprog" "/my/tree/share/locale")
2080          ⇒ "/my/tree/share/locale"
2081
2082     When using Autoconf/Automake, an application should arrange for the
2083     configured ‘localedir’ to get into the program (by substituting, or
2084     by generating a config file) and set that for its domain.  This
2085     ensures the catalogue can be found even when installed in a
2086     non-standard location.
2087
2088 -- Scheme Procedure: bind-textdomain-codeset domain [encoding]
2089 -- C Function: scm_bind_textdomain_codeset (domain, encoding)
2090     Get or set the text encoding to be used by ‘gettext’ for messages
2091     from DOMAIN.  ENCODING is a string, the name of a coding system,
2092     for instance "8859_1".  (On a Unix/POSIX system the ‘iconv’ program
2093     can list all available encodings.)
2094
2095     When called without an ENCODING the current setting is returned, or
2096     ‘#f’ if none yet set.  When called with an ENCODING, it is set for
2097     DOMAIN and that new setting returned.  For example,
2098
2099          (bind-textdomain-codeset "myprog")
2100          ⇒ #f
2101          (bind-textdomain-codeset "myprog" "latin-9")
2102          ⇒ "latin-9"
2103
2104     The encoding requested can be different from the translated data
2105     file, messages will be recoded as necessary.  But note that when
2106     there is no translation, ‘gettext’ returns its MSG unchanged, ie.
2107     without any recoding.  For that reason source message strings are
2108     best as plain ASCII.
2109
2110     Currently Guile has no understanding of multi-byte characters, and
2111     string functions won’t recognise character boundaries in multi-byte
2112     strings.  An application will at least be able to pass such strings
2113     through to some output though.  Perhaps this will change in the
2114     future.
2115
2116   ---------- Footnotes ----------
2117
2118   (1) Users of ‘gettext’ might be a bit surprised that ‘G_’ is the
2119conventional abbreviation for ‘gettext’.  In most other languages, the
2120conventional shorthand is ‘_’.  Guile uses ‘G_’ because ‘_’ is already
2121taken, as it is bound to a syntactic keyword used by ‘syntax-rules’,
2122‘match’, and other macros.
2123
2124
2125File: guile.info,  Node: Debugging,  Next: Code Coverage,  Prev: Internationalization,  Up: API Reference
2126
21276.26 Debugging Infrastructure
2128=============================
2129
2130In order to understand Guile’s debugging facilities, you first need to
2131understand a little about how Guile represents the Scheme control stack.
2132With that in place we explain the low level trap calls that the virtual
2133machine can be configured to make, and the trap and breakpoint
2134infrastructure that builds on top of those calls.
2135
2136* Menu:
2137
2138* Evaluation Model::            Evaluation and the Scheme stack.
2139* Source Properties::           From expressions to source locations.
2140* Programmatic Error Handling::  Debugging when an error occurs.
2141* Traps::                       Breakpoints, tracepoints, oh my!
2142* GDB Support::                 C-level debugging with GDB.
2143
2144
2145File: guile.info,  Node: Evaluation Model,  Next: Source Properties,  Up: Debugging
2146
21476.26.1 Evaluation and the Scheme Stack
2148--------------------------------------
2149
2150The idea of the Scheme stack is central to a lot of debugging.  The
2151Scheme stack is a reified representation of the pending function returns
2152in an expression’s continuation.  As Guile implements function calls
2153using a stack, this reification takes the form of a number of nested
2154stack frames, each of which corresponds to the application of a
2155procedure to a set of arguments.
2156
2157   A Scheme stack always exists implicitly, and can be summoned into
2158concrete existence as a first-class Scheme value by the ‘make-stack’
2159call, so that an introspective Scheme program – such as a debugger – can
2160present it in some way and allow the user to query its details.  The
2161first thing to understand, therefore, is how Guile’s function call
2162convention creates the stack.
2163
2164   Broadly speaking, Guile represents all control flow on a stack.
2165Calling a function involves pushing an empty frame on the stack, then
2166evaluating the procedure and its arguments, then fixing up the new frame
2167so that it points to the old one.  Frames on the stack are thus linked
2168together.  A tail call is the same, except it reuses the existing frame
2169instead of pushing on a new one.
2170
2171   In this way, the only frames that are on the stack are “active”
2172frames, frames which need to do some work before the computation is
2173complete.  On the other hand, a function that has tail-called another
2174function will not be on the stack, as it has no work left to do.
2175
2176   Therefore, when an error occurs in a running program, or the program
2177hits a breakpoint, or in fact at any point that the programmer chooses,
2178its state at that point can be represented by a “stack” of all the
2179procedure applications that are logically in progress at that time, each
2180of which is known as a “frame”.  The programmer can learn more about the
2181program’s state at that point by inspecting the stack and its frames.
2182
2183* Menu:
2184
2185* Stack Capture::               Reifying a continuation.
2186* Stacks::                      Accessors for the stack data type.
2187* Frames::                      Likewise, accessors for stack frames.
2188
2189
2190File: guile.info,  Node: Stack Capture,  Next: Stacks,  Up: Evaluation Model
2191
21926.26.1.1 Stack Capture
2193......................
2194
2195A Scheme program can use the ‘make-stack’ primitive anywhere in its
2196code, with first arg ‘#t’, to construct a Scheme value that describes
2197the Scheme stack at that point.
2198
2199     (make-stack #t)
22002201     #<stack 25205a0>
2202
2203   Use ‘start-stack’ to limit the stack extent captured by future
2204‘make-stack’ calls.
2205
2206 -- Scheme Procedure: make-stack obj arg ...
2207 -- C Function: scm_make_stack (obj, args)
2208     Create a new stack.  If OBJ is ‘#t’, the current evaluation stack
2209     is used for creating the stack frames, otherwise the frames are
2210     taken from OBJ (which must be a continuation or a frame object).
2211
2212     ARG ... can be any combination of integer, procedure, address
2213     range, and prompt tag values.
2214
2215     These values specify various ways of cutting away uninteresting
2216     stack frames from the top and bottom of the stack that ‘make-stack’
2217     returns.  They come in pairs like this: ‘(INNER_CUT_1 OUTER_CUT_1
2218     INNER_CUT_2 OUTER_CUT_2 ...)’.
2219
2220     Each INNER_CUT_I can be an integer, a procedure, an address range,
2221     or a prompt tag.  An integer means to cut away exactly that number
2222     of frames.  A procedure means to cut away all frames up to but
2223     excluding the frame whose procedure matches the specified one.  An
2224     address range is a pair of integers indicating the low and high
2225     addresses of a procedure’s code, and is the same as cutting away to
2226     a procedure (though with less work).  Anything else is interpreted
2227     as a prompt tag which cuts away all frames that are inside a prompt
2228     with the given tag.
2229
2230     Each OUTER_CUT_I can likewise be an integer, a procedure, an
2231     address range, or a prompt tag.  An integer means to cut away that
2232     number of frames.  A procedure means to cut away frames down to but
2233     excluding the frame whose procedure matches the specified one.  An
2234     address range is the same, but with the procedure’s code specified
2235     as an address range.  Anything else is taken to be a prompt tag,
2236     which cuts away all frames that are outside a prompt with the given
2237     tag.
2238
2239     If the OUTER_CUT_I of the last pair is missing, it is taken as 0.
2240
2241 -- Scheme Syntax: start-stack id exp
2242     Evaluate EXP on a new calling stack with identity ID.  If EXP is
2243     interrupted during evaluation, backtraces will not display frames
2244     farther back than EXP’s top-level form.  This macro is a way of
2245     artificially limiting backtraces and stack procedures, largely as a
2246     convenience to the user.
2247
2248
2249File: guile.info,  Node: Stacks,  Next: Frames,  Prev: Stack Capture,  Up: Evaluation Model
2250
22516.26.1.2 Stacks
2252...............
2253
2254 -- Scheme Procedure: stack? obj
2255 -- C Function: scm_stack_p (obj)
2256     Return ‘#t’ if OBJ is a calling stack.
2257
2258 -- Scheme Procedure: stack-id stack
2259 -- C Function: scm_stack_id (stack)
2260     Return the identifier given to STACK by ‘start-stack’.
2261
2262 -- Scheme Procedure: stack-length stack
2263 -- C Function: scm_stack_length (stack)
2264     Return the length of STACK.
2265
2266 -- Scheme Procedure: stack-ref stack index
2267 -- C Function: scm_stack_ref (stack, index)
2268     Return the INDEX’th frame from STACK.
2269
2270 -- Scheme Procedure: display-backtrace stack port [first [depth
2271          [highlights]]]
2272 -- C Function: scm_display_backtrace_with_highlights (stack, port,
2273          first, depth, highlights)
2274 -- C Function: scm_display_backtrace (stack, port, first, depth)
2275     Display a backtrace to the output port PORT.  STACK is the stack to
2276     take the backtrace from, FIRST specifies where in the stack to
2277     start and DEPTH how many frames to display.  FIRST and DEPTH can be
2278     ‘#f’, which means that default values will be used.  If HIGHLIGHTS
2279     is given it should be a list; the elements of this list will be
2280     highlighted wherever they appear in the backtrace.
2281
2282
2283File: guile.info,  Node: Frames,  Prev: Stacks,  Up: Evaluation Model
2284
22856.26.1.3 Frames
2286...............
2287
2288 -- Scheme Procedure: frame? obj
2289 -- C Function: scm_frame_p (obj)
2290     Return ‘#t’ if OBJ is a stack frame.
2291
2292 -- Scheme Procedure: frame-previous frame
2293 -- C Function: scm_frame_previous (frame)
2294     Return the previous frame of FRAME, or ‘#f’ if FRAME is the first
2295     frame in its stack.
2296
2297 -- Scheme Procedure: frame-procedure-name frame
2298 -- C Function: scm_frame_procedure_name (frame)
2299     Return the name of the procedure being applied in FRAME, as a
2300     symbol, or ‘#f’ if the procedure has no name.
2301
2302 -- Scheme Procedure: frame-arguments frame
2303 -- C Function: scm_frame_arguments (frame)
2304     Return the arguments of FRAME.
2305
2306 -- Scheme Procedure: frame-address frame
2307 -- Scheme Procedure: frame-instruction-pointer frame
2308 -- Scheme Procedure: frame-stack-pointer frame
2309     Accessors for the three VM registers associated with this frame:
2310     the frame pointer (fp), instruction pointer (ip), and stack pointer
2311     (sp), respectively.  *Note VM Concepts::, for more information.
2312
2313 -- Scheme Procedure: frame-dynamic-link frame
2314 -- Scheme Procedure: frame-return-address frame
2315 -- Scheme Procedure: frame-mv-return-address frame
2316     Accessors for the three saved VM registers in a frame: the previous
2317     frame pointer, the single-value return address, and the
2318     multiple-value return address.  *Note Stack Layout::, for more
2319     information.
2320
2321 -- Scheme Procedure: frame-bindings frame
2322     Return a list of binding records indicating the local variables
2323     that are live in a frame.
2324
2325 -- Scheme Procedure: frame-lookup-binding frame var
2326     Fetch the bindings in FRAME, and return the first one whose name is
2327     VAR, or ‘#f’ otherwise.
2328
2329 -- Scheme Procedure: binding-index binding
2330 -- Scheme Procedure: binding-name binding
2331 -- Scheme Procedure: binding-slot binding
2332 -- Scheme Procedure: binding-representation binding
2333     Accessors for the various fields in a binding.  The implicit
2334     “callee” argument is index 0, the first argument is index 1, and so
2335     on to the end of the arguments.  After that are temporary
2336     variables.  Note that if a variable is dead, it might not be
2337     available.
2338
2339 -- Scheme Procedure: binding-ref binding
2340 -- Scheme Procedure: binding-set! binding val
2341     Accessors for the values of local variables in a frame.
2342
2343 -- Scheme Procedure: display-application frame [port [indent]]
2344 -- C Function: scm_display_application (frame, port, indent)
2345     Display a procedure application FRAME to the output port PORT.
2346     INDENT specifies the indentation of the output.
2347
2348   Additionally, the ‘(system vm frame)’ module defines a number of
2349higher-level introspective procedures, for example to retrieve the names
2350of local variables, and the source location to correspond to a frame.
2351See its source code for more details.
2352
2353
2354File: guile.info,  Node: Source Properties,  Next: Programmatic Error Handling,  Prev: Evaluation Model,  Up: Debugging
2355
23566.26.2 Source Properties
2357------------------------
2358
2359How best to associate source locations with datums parsed from a port?
2360The right way to do this is to annotate all components of each parsed
2361datum.  *Note Annotated Scheme Read::, for more on ‘read-syntax’.
2362
2363   Guile only switched to use ‘read-syntax’ in 2021, however.  For the
2364previous thirty years, it used a mechanism known as “source properties”.
2365
2366   As Guile reads in Scheme code from file or from standard input, it
2367can record the file name, line number and column number where each
2368expression begins in a side table.
2369
2370   The way that this side table associates datums with source properties
2371has a limitation, however: Guile can only associate source properties
2372with freshly allocated objects.  This notably excludes individual
2373symbols, keywords, characters, booleans, or small integers.  This
2374limitation finally motivated the switch to ‘read-syntax’.
2375
2376 -- Scheme Procedure: supports-source-properties? obj
2377 -- C Function: scm_supports_source_properties_p (obj)
2378     Return #t if source properties can be associated with OBJ,
2379     otherwise return #f.
2380
2381   The recording of source properties is controlled by the read option
2382named “positions” (*note Scheme Read::).  This option is switched _on_
2383by default.  Now that ‘read-syntax’ is available, however, Guile may
2384change the default for this flag to off in the future.
2385
2386   The following procedures can be used to access and set the source
2387properties of read expressions.
2388
2389 -- Scheme Procedure: set-source-properties! obj alist
2390 -- C Function: scm_set_source_properties_x (obj, alist)
2391     Install the association list ALIST as the source property list for
2392     OBJ.
2393
2394 -- Scheme Procedure: set-source-property! obj key datum
2395 -- C Function: scm_set_source_property_x (obj, key, datum)
2396     Set the source property of object OBJ, which is specified by KEY to
2397     DATUM.  Normally, the key will be a symbol.
2398
2399 -- Scheme Procedure: source-properties obj
2400 -- C Function: scm_source_properties (obj)
2401     Return the source property association list of OBJ.
2402
2403 -- Scheme Procedure: source-property obj key
2404 -- C Function: scm_source_property (obj, key)
2405     Return the property specified by KEY from OBJ’s source properties.
2406
2407   If the ‘positions’ reader option is enabled, supported expressions
2408will have values set for the ‘filename’, ‘line’ and ‘column’ properties.
2409
2410   Source properties are also associated with syntax objects.
2411Procedural macros can get at the source location of their input using
2412the ‘syntax-source’ accessor.  *Note Syntax Transformer Helpers::, for
2413more.
2414
2415   Guile also defines a couple of convenience macros built on
2416‘syntax-source’:
2417
2418 -- Scheme Syntax: current-source-location
2419     Expands to the source properties corresponding to the location of
2420     the ‘(current-source-location)’ form.
2421
2422 -- Scheme Syntax: current-filename
2423     Expands to the current filename: the filename that the
2424     ‘(current-filename)’ form appears in.  Expands to ‘#f’ if this
2425     information is unavailable.
2426
2427   If you’re stuck with defmacros (*note Defmacros::), and want to
2428preserve source information, the following helper function might be
2429useful to you:
2430
2431 -- Scheme Procedure: cons-source xorig x y
2432 -- C Function: scm_cons_source (xorig, x, y)
2433     Create and return a new pair whose car and cdr are X and Y.  Any
2434     source properties associated with XORIG are also associated with
2435     the new pair.
2436
2437
2438File: guile.info,  Node: Programmatic Error Handling,  Next: Traps,  Prev: Source Properties,  Up: Debugging
2439
24406.26.3 Programmatic Error Handling
2441----------------------------------
2442
2443For better or for worse, all programs have bugs, and dealing with bugs
2444is part of programming.  This section deals with that class of bugs that
2445causes an exception to be raised – from your own code, from within a
2446library, or from Guile itself.
2447
2448* Menu:
2449
2450* Catching Exceptions::    Handling errors after the stack is unwound.
2451* Pre-Unwind Debugging::   Debugging before the exception is thrown.
2452* Standard Error Handling:: Call-with-error-handling.
2453* Stack Overflow::         Detecting and handling runaway recursion.
2454* Debug Options::          A historical interface to debugging.
2455
2456
2457File: guile.info,  Node: Catching Exceptions,  Next: Pre-Unwind Debugging,  Up: Programmatic Error Handling
2458
24596.26.3.1 Catching Exceptions
2460............................
2461
2462A common requirement is to be able to show as much useful context as
2463possible when a Scheme program hits an error.  The most immediate
2464information about an error is the kind of error that it is – such as
2465“division by zero” – and any parameters that the code which signalled
2466the error chose explicitly to provide.  This information originates with
2467the ‘error’ or ‘raise-exception’ call (or their C code equivalents, if
2468the error is detected by C code) that signals the error, and is passed
2469automatically to the handler procedure of the innermost applicable
2470exception handler.
2471
2472   Therefore, to catch errors that occur within a chunk of Scheme code,
2473and to intercept basic information about those errors, you need to
2474execute that code inside the dynamic context of a
2475‘with-exception-handler’, or the equivalent in C.
2476
2477   For example, to print out a message and return #f when an error
2478occurs, you might use:
2479
2480     (define (catch-all thunk)
2481       (with-exception-handler
2482         (lambda (exn)
2483           (format (current-error-port)
2484                   "Uncaught exception: ~s\n" exn)
2485           #f)
2486         thunk
2487         #:unwind? #t))
2488
2489     (catch-all
2490      (lambda () (error "Not a vegetable: tomato")))
2491     ⊣ Uncaught exception: #<&exception-with-kind-and-args ...>
2492     ⇒ #f
2493
2494   *Note Exceptions::, for full details.
2495
2496
2497File: guile.info,  Node: Pre-Unwind Debugging,  Next: Standard Error Handling,  Prev: Catching Exceptions,  Up: Programmatic Error Handling
2498
24996.26.3.2 Pre-Unwind Debugging
2500.............................
2501
2502Sometimes when something goes wrong, what you want is not just a
2503representation of the exceptional situation, but the context that
2504brought about that situation.  The example in the previous section
2505passed ‘#:unwind #t’ to ‘with-exception-handler’, indicating that
2506‘raise-exception’ should unwind the stack before invoking the exception
2507handler.  However if you don’t take this approach and instead let the
2508exception handler be invoked in the context of the ‘raise-exception’,
2509you can print a backtrace, launch a recursive debugger, or take other
2510“pre-unwind” actions.
2511
2512   The most basic idea would be to simply print a backtrace:
2513
2514     (define (call-with-backtrace thunk)
2515       (with-exception-handler
2516         (lambda (exn)
2517           (backtrace)
2518           (raise-exception exn))
2519         thunk))
2520
2521   Here we use the built-in ‘backtrace’ procedure to print the
2522backtrace.
2523
2524 -- Scheme Procedure: backtrace [highlights]
2525 -- C Function: scm_backtrace_with_highlights (highlights)
2526 -- C Function: scm_backtrace ()
2527     Display a backtrace of the current stack to the current output
2528     port.  If HIGHLIGHTS is given it should be a list; the elements of
2529     this list will be highlighted wherever they appear in the
2530     backtrace.
2531
2532   By re-raising the exception, ‘call-with-backtrace’ doesn’t actually
2533handle the error.  We could define a version that instead aborts the
2534computation:
2535
2536     (use-modules (ice-9 control))
2537     (define (call-with-backtrace thunk)
2538       (let/ec cancel
2539         (with-exception-handler
2540           (lambda (exn)
2541             (backtrace)
2542             (cancel #f))
2543           thunk)))
2544
2545   In this second example, we use an escape continuation to abort the
2546computation after printing the backtrace, returning ‘#f’ instead.
2547
2548   It could be that you want to only print a limited backtrace.  In that
2549case, use ‘start-stack’:
2550
2551     (use-modules (ice-9 control))
2552     (define (call-with-backtrace thunk)
2553       (let/ec cancel
2554         (start-stack 'stack-with-backtrace
2555           (with-exception-handler
2556             (lambda (exn)
2557               (backtrace)
2558               (cancel #f))
2559             thunk))))
2560
2561   There are also more powerful, programmatic ways to walk the stack
2562using ‘make-stack’ and friends; see the API described in *note Stacks::
2563and *note Frames::.
2564
2565
2566File: guile.info,  Node: Standard Error Handling,  Next: Stack Overflow,  Prev: Pre-Unwind Debugging,  Up: Programmatic Error Handling
2567
25686.26.3.3 call-with-error-handling
2569.................................
2570
2571The Guile REPL code (in ‘system/repl/repl.scm’ and related files) uses a
2572‘catch’ with a pre-unwind handler to capture the stack when an error
2573occurs in an expression that was typed into the REPL, and debug that
2574stack interactively in the context of the error.
2575
2576   These procedures are available for use by user programs, in the
2577‘(system repl error-handling)’ module.
2578
2579     (use-modules (system repl error-handling))
2580
2581 -- Scheme Procedure: call-with-error-handling thunk [#:on-error
2582          on-error='debug] [#:post-error post-error='catch] [#:pass-keys
2583          pass-keys='(quit)] [#:report-keys
2584          report-keys='(stack-overflow)] [#:trap-handler
2585          trap-handler='debug]
2586     Call a thunk in a context in which errors are handled.
2587
2588     Note that this function was written when ‘throw’/‘catch’ were the
2589     fundamental exception handling primitives in Guile, and so exposes
2590     some aspects of that interface (notably in the form of the
2591     procedural handlers).  Guile will probably replace this function
2592     with a ‘call-with-standard-exception-handling’ in the future.
2593
2594     There are five keyword arguments:
2595
2596     ON-ERROR
2597          Specifies what to do before the stack is unwound.
2598
2599          Valid options are ‘debug’ (the default), which will enter a
2600          debugger; ‘pass’, in which case nothing is done, and the
2601          exception is rethrown; or a procedure, which will be the
2602          pre-unwind handler.
2603
2604     POST-ERROR
2605          Specifies what to do after the stack is unwound.
2606
2607          Valid options are ‘catch’ (the default), which will silently
2608          catch errors, returning the unspecified value; ‘report’, which
2609          prints out a description of the error (via ‘display-error’),
2610          and then returns the unspecified value; or a procedure, which
2611          will be the catch handler.
2612
2613     TRAP-HANDLER
2614          Specifies a trap handler: what to do when a breakpoint is hit.
2615
2616          Valid options are ‘debug’, which will enter the debugger;
2617          ‘pass’, which does nothing; or ‘disabled’, which disables
2618          traps entirely.  *Note Traps::, for more information.
2619
2620     PASS-KEYS
2621          A set of keys to ignore, as a list.
2622
2623     REPORT-KEYS
2624          A set of keys to always report even if the post-error handler
2625          is ‘catch’, as a list.
2626
2627
2628File: guile.info,  Node: Stack Overflow,  Next: Debug Options,  Prev: Standard Error Handling,  Up: Programmatic Error Handling
2629
26306.26.3.4 Stack Overflow
2631.......................
2632
2633Every time a Scheme program makes a call that is not in tail position,
2634it pushes a new frame onto the stack.  Returning a value from a function
2635pops the top frame off the stack.  Stack frames take up memory, and as
2636nobody has an infinite amount of memory, deep recursion could cause
2637Guile to run out of memory.  Running out of stack memory is called
2638“stack overflow”.
2639
2640Stack Limits
2641............
2642
2643Most languages have a terrible stack overflow story.  For example, in C,
2644if you use too much stack, your program will exhibit “undefined
2645behavior”, which if you are lucky means that it will crash.  It’s
2646especially bad in C, as you neither know ahead of time how much stack
2647your functions use, nor the stack limit imposed by the user’s system,
2648and the stack limit is often quite small relative to the total memory
2649size.
2650
2651   Managed languages like Python have a better error story, as they are
2652defined to raise an exception on stack overflow – but like C, Python and
2653most dynamic languages still have a fixed stack size limit that is
2654usually much smaller than the heap.
2655
2656   Arbitrary stack limits would have an unfortunate effect on Guile
2657programs.  For example, the following implementation of the inner loop
2658of ‘map’ is clean and elegant:
2659
2660     (define (map f l)
2661       (if (pair? l)
2662           (cons (f (car l))
2663                 (map f (cdr l)))
2664           '()))
2665
2666   However, if there were a stack limit, that would limit the size of
2667lists that can be processed with this ‘map’.  Eventually, you would have
2668to rewrite it to use iteration with an accumulator:
2669
2670     (define (map f l)
2671       (let lp ((l l) (out '()))
2672         (if (pair? l)
2673             (lp (cdr l) (cons (f (car l)) out))
2674             (reverse out))))
2675
2676   This second version is sadly not as clear, and it also allocates more
2677heap memory (once to build the list in reverse, and then again to
2678reverse the list).  You would be tempted to use the destructive
2679‘reverse!’ to save memory and time, but then your code would not be
2680continuation-safe – if F returned again after the map had finished, it
2681would see an OUT list that had already been reversed.  The recursive
2682‘map’ has none of these problems.
2683
2684   Guile has no stack limit for Scheme code.  When a thread makes its
2685first Guile call, a small stack is allocated – just one page of memory.
2686Whenever that memory limit would be reached, Guile arranges to grow the
2687stack by a factor of two.  When garbage collection happens, Guile
2688arranges to return the unused part of the stack to the operating system,
2689but without causing the stack to shrink.  In this way, the stack can
2690grow to consume up to all memory available to the Guile process, and
2691when the recursive computation eventually finishes, that stack memory is
2692returned to the system.
2693
2694Exceptional Situations
2695......................
2696
2697Of course, it’s still possible to run out of stack memory.  The most
2698common cause of this is program bugs that cause unbounded recursion, as
2699in:
2700
2701     (define (faulty-map f l)
2702       (if (pair? l)
2703           (cons (f (car l)) (faulty-map f l))
2704           '()))
2705
2706   Did you spot the bug?  The recursive call to ‘faulty-map’ recursed on
2707L, not ‘(cdr L)’.  Running this program would cause Guile to use up all
2708memory in your system, and eventually Guile would fail to grow the
2709stack.  At that point you have a problem: Guile needs to raise an
2710exception to unwind the stack and return memory to the system, but the
2711user might have exception handlers in place (*note Raising and Handling
2712Exceptions::) that want to run before the stack is unwound, and we don’t
2713have any stack in which to run them.
2714
2715   Therefore in this case, Guile raises an unwind-only exception that
2716does not run pre-unwind handlers.  Because this is such an odd case,
2717Guile prints out a message on the console, in case the user was
2718expecting to be able to get a backtrace from any pre-unwind handler.
2719
2720Runaway Recursion
2721.................
2722
2723Still, this failure mode is not so nice.  If you are running an
2724environment in which you are interactively building a program while it
2725is running, such as at a REPL, you might want to impose an artificial
2726stack limit on the part of your program that you are building to detect
2727accidental runaway recursion.  For that purpose, there is
2728‘call-with-stack-overflow-handler’, from ‘(system vm vm)’.
2729
2730     (use-module (system vm vm))
2731
2732 -- Scheme Procedure: call-with-stack-overflow-handler limit thunk
2733          handler
2734     Call THUNK in an environment in which the stack limit has been
2735     reduced to LIMIT additional words.  If the limit is reached,
2736     HANDLER (a thunk) will be invoked in the dynamic environment of the
2737     error.  For the extent of the call to HANDLER, the stack limit and
2738     handler are restored to the values that were in place when
2739     ‘call-with-stack-overflow-handler’ was called.
2740
2741     Usually, HANDLER should raise an exception or abort to an outer
2742     prompt.  However if HANDLER does return, it should return a number
2743     of additional words of stack space to allow to the inner
2744     environment.
2745
2746   A stack overflow handler may only ever “credit” the inner thunk with
2747stack space that was available when the handler was instated.  When
2748Guile first starts, there is no stack limit in place, so the outer
2749handler may allow the inner thunk an arbitrary amount of space, but any
2750nested stack overflow handler will not be able to consume more than its
2751limit.
2752
2753   Unlike the unwind-only exception that is thrown if Guile is unable to
2754grow its stack, any exception thrown by a stack overflow handler might
2755invoke pre-unwind handlers.  Indeed, the stack overflow handler is
2756itself a pre-unwind handler of sorts.  If the code imposing the stack
2757limit wants to protect itself against malicious pre-unwind handlers from
2758the inner thunk, it should abort to a prompt of its own making instead
2759of throwing an exception that might be caught by the inner thunk.
2760
2761C Stack Usage
2762.............
2763
2764It is also possible for Guile to run out of space on the C stack.  If
2765you call a primitive procedure which then calls a Scheme procedure in a
2766loop, you will consume C stack space.  Guile tries to detect excessive
2767consumption of C stack space, throwing an error when you have hit 80% of
2768the process’ available stack (as allocated by the operating system), or
2769160 kilowords in the absence of a strict limit.
2770
2771   For example, looping through ‘call-with-vm’, a primitive that calls a
2772thunk, gives us the following:
2773
2774     scheme@(guile-user)> (use-modules (system vm vm))
2775     scheme@(guile-user)> (let lp () (call-with-vm lp))
2776     ERROR: Stack overflow
2777
2778   Unfortunately, that’s all the information we get.  Overrunning the C
2779stack will throw an unwind-only exception, because it’s not safe to do
2780very much when you are close to the C stack limit.
2781
2782   If you get an error like this, you can either try rewriting your code
2783to use less stack space, or increase the maximum stack size.  To
2784increase the maximum stack size, use ‘debug-set!’, for example:
2785
2786     (debug-set! stack 200000)
2787
2788   The next section describes ‘debug-set!’ more thoroughly.  Of course
2789the best thing is to have your code operate without so much resource
2790consumption by avoiding loops through C trampolines.
2791
2792
2793File: guile.info,  Node: Debug Options,  Prev: Stack Overflow,  Up: Programmatic Error Handling
2794
27956.26.3.5 Debug options
2796......................
2797
2798The behavior of the ‘backtrace’ procedure and of the default error
2799handler can be parameterized via the debug options.
2800
2801 -- Scheme Procedure: debug-options [setting]
2802     Display the current settings of the debug options.  If SETTING is
2803     omitted, only a short form of the current read options is printed.
2804     Otherwise if SETTING is the symbol ‘help’, a complete options
2805     description is displayed.
2806
2807   The set of available options, and their default values, may be had by
2808invoking ‘debug-options’ at the prompt.
2809
2810     scheme@(guile-user)>
2811     backwards       no      Display backtrace in anti-chronological order.
2812     width           79      Maximal width of backtrace.
2813     depth           20      Maximal length of printed backtrace.
2814     backtrace       yes     Show backtrace on error.
2815     stack           1048576 Stack size limit (measured in words;
2816                             0 = no check).
2817     show-file-name  #t      Show file names and line numbers in backtraces
2818                             when not `#f'.  A value of `base' displays only
2819                             base names, while `#t' displays full names.
2820     warn-deprecated no      Warn when deprecated features are used.
2821
2822   The boolean options may be toggled with ‘debug-enable’ and
2823‘debug-disable’.  The non-boolean options must be set using
2824‘debug-set!’.
2825
2826 -- Scheme Procedure: debug-enable option-name
2827 -- Scheme Procedure: debug-disable option-name
2828 -- Scheme Syntax: debug-set! option-name value
2829     Modify the debug options.  ‘debug-enable’ should be used with
2830     boolean options and switches them on, ‘debug-disable’ switches them
2831     off.
2832
2833     ‘debug-set!’ can be used to set an option to a specific value.  Due
2834     to historical oddities, it is a macro that expects an unquoted
2835     option name.
2836
2837
2838File: guile.info,  Node: Traps,  Next: GDB Support,  Prev: Programmatic Error Handling,  Up: Debugging
2839
28406.26.4 Traps
2841------------
2842
2843Guile’s virtual machine can be configured to call out at key points to
2844arbitrary user-specified procedures.
2845
2846   In principle, these “hooks” allow Scheme code to implement any model
2847it chooses for examining the evaluation stack as program execution
2848proceeds, and for suspending execution to be resumed later.
2849
2850   VM hooks are very low-level, though, and so Guile also has a library
2851of higher-level “traps” on top of the VM hooks.  A trap is an execution
2852condition that, when fulfilled, will fire a handler.  For example, Guile
2853defines a trap that fires when control reaches a certain source
2854location.
2855
2856   Finally, Guile also defines a third level of abstractions: per-thread
2857“trap states”.  A trap state exists to give names to traps, and to hold
2858on to the set of traps so that they can be enabled, disabled, or
2859removed.  The trap state infrastructure defines the most useful
2860abstractions for most cases.  For example, Guile’s REPL uses trap state
2861functions to set breakpoints and tracepoints.
2862
2863   The following subsections describe all this in detail, for both the
2864user wanting to use traps, and the developer interested in understanding
2865how the interface hangs together.
2866
2867* Menu:
2868
2869* VM Hooks::                Modifying Guile’s virtual machine.
2870* Trap Interface::          Traps are on or off.
2871* Low-Level Traps::         The various kinds of low-level traps.
2872* Tracing Traps::           Traps to trace procedure calls and returns.
2873* Trap States::             One state (per thread) to bind them.
2874* High-Level Traps::        The highest-level trap interface. Use this.
2875
2876
2877File: guile.info,  Node: VM Hooks,  Next: Trap Interface,  Up: Traps
2878
28796.26.4.1 VM Hooks
2880.................
2881
2882Everything that runs in Guile runs on its virtual machine, a C program
2883that defines a number of operations that Scheme programs can perform.
2884
2885   Note that there are multiple VM “engines” for Guile.  Only some of
2886them have support for hooks compiled in.  Normally the deal is that you
2887get hooks if you are running interactively, and otherwise they are
2888disabled, as they do have some overhead (about 10 or 20 percent).
2889
2890   To ensure that you are running with hooks, pass ‘--debug’ to Guile
2891when running your program, or otherwise use the ‘call-with-vm’ and
2892‘set-vm-engine!’ procedures to ensure that you are running in a VM with
2893the ‘debug’ engine.
2894
2895   To digress, Guile’s VM has 4 different hooks that can be fired at
2896different times.  For implementation reasons, these hooks are not
2897actually implemented with first-class Scheme hooks (*note Hooks::); they
2898are managed using an ad-hoc interface.
2899
2900   VM hooks are called with one argument: the current frame.  *Note
2901Frames::.  Since these hooks may be fired very frequently, Guile does a
2902terrible thing: it allocates the frames on the C stack instead of the
2903garbage-collected heap.
2904
2905   The upshot here is that the frames are only valid within the dynamic
2906extent of the call to the hook.  If a hook procedure keeps a reference
2907to the frame outside the extent of the hook, bad things will happen.
2908
2909   The interface to hooks is provided by the ‘(system vm vm)’ module:
2910
2911     (use-modules (system vm vm))
2912
2913All of these functions implicitly act on the VM for the current thread
2914only.
2915
2916 -- Scheme Procedure: vm-add-next-hook! f
2917     Arrange to call F when before an instruction is retired (and
2918     executed).
2919
2920 -- Scheme Procedure: vm-add-apply-hook! f
2921     Arrange to call F whenever a procedure is applied.  The frame
2922     locals will be the callee, followed by the arguments to the call.
2923
2924     Note that procedure application is somewhat orthogonal to
2925     continuation pushes and pops.  To know whether a call is a tail
2926     call or not, with respect to the frame previously in place, check
2927     the value of the frame pointer compared the previous frame pointer.
2928
2929 -- Scheme Procedure: vm-add-return-hook! f
2930     Arrange to call F before returning from a frame.  The values in the
2931     frame will be the frame’s return values.
2932
2933     Note that it’s possible to return from an “inner” frame: one that
2934     was not immediately proceeded by a call with that frame pointer.
2935     In that case, it corresponds to a non-local control flow jump,
2936     either because of applying a composable continuation or because of
2937     restoring a saved undelimited continuation.
2938
2939 -- Scheme Procedure: vm-add-abort-hook!
2940     Arrange to call F after aborting to a prompt.  *Note Prompts::.
2941
2942     Unfortunately, the values passed to the prompt handler are not
2943     easily available to F.
2944
2945 -- Scheme Procedure: vm-remove-next-hook! f
2946 -- Scheme Procedure: vm-remove-apply-hook! f
2947 -- Scheme Procedure: vm-remove-return-hook! f
2948 -- Scheme Procedure: vm-remove-abort-hook! f
2949     Remove F from the corresponding VM hook for the current thread.
2950
2951   These hooks do impose a performance penalty, if they are on.
2952Obviously, the ‘vm-next-hook’ has quite an impact, performance-wise.
2953Therefore Guile exposes a single, heavy-handed knob to turn hooks on or
2954off, the “VM trace level”.  If the trace level is positive, hooks run;
2955otherwise they don’t.
2956
2957   For convenience, when the VM fires a hook, it does so with the trap
2958level temporarily set to 0.  That way the hooks don’t fire while you’re
2959handling a hook.  The trace level is restored to whatever it was once
2960the hook procedure finishes.
2961
2962 -- Scheme Procedure: vm-trace-level
2963     Retrieve the “trace level” of the VM. If positive, the trace hooks
2964     associated with VM will be run.  The initial trace level is 0.
2965
2966 -- Scheme Procedure: set-vm-trace-level! level
2967     Set the “trace level” of the VM.
2968
2969   *Note A Virtual Machine for Guile::, for more information on Guile’s
2970virtual machine.
2971
2972
2973File: guile.info,  Node: Trap Interface,  Next: Low-Level Traps,  Prev: VM Hooks,  Up: Traps
2974
29756.26.4.2 Trap Interface
2976.......................
2977
2978The capabilities provided by hooks are great, but hooks alone rarely
2979correspond to what users want to do.
2980
2981   For example, if a user wants to break when and if control reaches a
2982certain source location, how do you do it?  If you install a “next”
2983hook, you get unacceptable overhead for the execution of the entire
2984program.  It would be possible to install an “apply” hook, then if the
2985procedure encompasses those source locations, install a “next” hook, but
2986already you’re talking about one concept that might be implemented by a
2987varying number of lower-level concepts.
2988
2989   It’s best to be clear about things and define one abstraction for all
2990such conditions: the “trap”.
2991
2992   Considering the myriad capabilities offered by the hooks though,
2993there is only a minimum of functionality shared by all traps.  Guile’s
2994current take is to reduce this to the absolute minimum, and have the
2995only standard interface of a trap be “turn yourself on” or “turn
2996yourself off”.
2997
2998   This interface sounds a bit strange, but it is useful to procedurally
2999compose higher-level traps from lower-level building blocks.  For
3000example, Guile defines a trap that calls one handler when control enters
3001a procedure, and another when control leaves the procedure.  Given that
3002trap, one can define a trap that adds to the next-hook only when within
3003a given procedure.  Building further, one can define a trap that fires
3004when control reaches particular instructions within a procedure.
3005
3006   Or of course you can stop at any of these intermediate levels.  For
3007example, one might only be interested in calls to a given procedure.
3008But the point is that a simple enable/disable interface is all the
3009commonality that exists between the various kinds of traps, and
3010furthermore that such an interface serves to allow “higher-level” traps
3011to be composed from more primitive ones.
3012
3013   Specifically, a trap, in Guile, is a procedure.  When a trap is
3014created, by convention the trap is enabled; therefore, the procedure
3015that is the trap will, when called, disable the trap, and return a
3016procedure that will enable the trap, and so on.
3017
3018   Trap procedures take one optional argument: the current frame.  (A
3019trap may want to add to different sets of hooks depending on the frame
3020that is current at enable-time.)
3021
3022   If this all sounds very complicated, it’s because it is.  Some of it
3023is essential, but probably most of it is not.  The advantage of using
3024this minimal interface is that composability is more lexically apparent
3025than when, for example, using a stateful interface based on GOOPS. But
3026perhaps this reflects the cognitive limitations of the programmer who
3027made the current interface more than anything else.
3028
3029
3030File: guile.info,  Node: Low-Level Traps,  Next: Tracing Traps,  Prev: Trap Interface,  Up: Traps
3031
30326.26.4.3 Low-Level Traps
3033........................
3034
3035To summarize the last sections, traps are enabled or disabled, and when
3036they are enabled, they add to various VM hooks.
3037
3038   Note, however, that _traps do not increase the VM trace level_.  So
3039if you create a trap, it will be enabled, but unless something else
3040increases the VM’s trace level (*note VM Hooks::), the trap will not
3041fire.  It turns out that getting the VM trace level right is tricky
3042without a global view of what traps are enabled.  *Note Trap States::,
3043for Guile’s answer to this problem.
3044
3045   Traps are created by calling procedures.  Most of these procedures
3046share a set of common keyword arguments, so rather than document them
3047separately, we discuss them all together here:
3048
3049‘#:vm’
3050     The VM to instrument.  Defaults to the current thread’s VM.
3051‘#:current-frame’
3052     For traps that enable more hooks depending on their dynamic
3053     context, this argument gives the current frame that the trap is
3054     running in.  Defaults to ‘#f’.
3055
3056   To have access to these procedures, you’ll need to have imported the
3057‘(system vm traps)’ module:
3058
3059     (use-modules (system vm traps))
3060
3061 -- Scheme Procedure: trap-at-procedure-call proc handler [#:vm]
3062     A trap that calls HANDLER when PROC is applied.
3063
3064 -- Scheme Procedure: trap-in-procedure proc enter-handler exit-handler
3065          [#:current-frame] [#:vm]
3066     A trap that calls ENTER-HANDLER when control enters PROC, and
3067     EXIT-HANDLER when control leaves PROC.
3068
3069     Control can enter a procedure via:
3070        • A procedure call.
3071        • A return to a procedure’s frame on the stack.
3072        • A continuation returning directly to an application of this
3073          procedure.
3074
3075     Control can leave a procedure via:
3076        • A normal return from the procedure.
3077        • An application of another procedure.
3078        • An invocation of a continuation.
3079        • An abort.
3080
3081 -- Scheme Procedure: trap-instructions-in-procedure proc next-handler
3082          exit-handler [#:current-frame] [#:vm]
3083     A trap that calls NEXT-HANDLER for every instruction executed in
3084     PROC, and EXIT-HANDLER when execution leaves PROC.
3085
3086 -- Scheme Procedure: trap-at-procedure-ip-in-range proc range handler
3087          [#:current-frame] [#:vm]
3088     A trap that calls HANDLER when execution enters a range of
3089     instructions in PROC.  RANGE is a simple of pairs, ‘((START . END)
3090     ...)’.  The START addresses are inclusive, and END addresses are
3091     exclusive.
3092
3093 -- Scheme Procedure: trap-at-source-location file user-line handler
3094          [#:current-frame] [#:vm]
3095     A trap that fires when control reaches a given source location.
3096     The USER-LINE parameter is one-indexed, as a user counts lines,
3097     instead of zero-indexed, as Guile counts lines.
3098
3099 -- Scheme Procedure: trap-frame-finish frame return-handler
3100          abort-handler [#:vm]
3101     A trap that fires when control leaves the given frame.  FRAME
3102     should be a live frame in the current continuation.  RETURN-HANDLER
3103     will be called on a normal return, and ABORT-HANDLER on a nonlocal
3104     exit.
3105
3106 -- Scheme Procedure: trap-in-dynamic-extent proc enter-handler
3107          return-handler abort-handler [#:vm]
3108     A more traditional dynamic-wind trap, which fires ENTER-HANDLER
3109     when control enters PROC, RETURN-HANDLER on a normal return, and
3110     ABORT-HANDLER on a nonlocal exit.
3111
3112     Note that rewinds are not handled, so there is no rewind handler.
3113
3114 -- Scheme Procedure: trap-calls-in-dynamic-extent proc apply-handler
3115          return-handler [#:current-frame] [#:vm]
3116     A trap that calls APPLY-HANDLER every time a procedure is applied,
3117     and RETURN-HANDLER for returns, but only during the dynamic extent
3118     of an application of PROC.
3119
3120 -- Scheme Procedure: trap-instructions-in-dynamic-extent proc
3121          next-handler [#:current-frame] [#:vm]
3122     A trap that calls NEXT-HANDLER for all retired instructions within
3123     the dynamic extent of a call to PROC.
3124
3125 -- Scheme Procedure: trap-calls-to-procedure proc apply-handler
3126          return-handler [#:vm]
3127     A trap that calls APPLY-HANDLER whenever PROC is applied, and
3128     RETURN-HANDLER when it returns, but with an additional argument,
3129     the call depth.
3130
3131     That is to say, the handlers will get two arguments: the frame in
3132     question, and the call depth (a non-negative integer).
3133
3134 -- Scheme Procedure: trap-matching-instructions frame-pred handler
3135          [#:vm]
3136     A trap that calls FRAME-PRED at every instruction, and if
3137     FRAME-PRED returns a true value, calls HANDLER on the frame.
3138
3139
3140File: guile.info,  Node: Tracing Traps,  Next: Trap States,  Prev: Low-Level Traps,  Up: Traps
3141
31426.26.4.4 Tracing Traps
3143......................
3144
3145The ‘(system vm trace)’ module defines a number of traps for tracing of
3146procedure applications.  When a procedure is “traced”, it means that
3147every call to that procedure is reported to the user during a program
3148run.  The idea is that you can mark a collection of procedures for
3149tracing, and Guile will subsequently print out a line of the form
3150
3151     |  |  (PROCEDURE ARGS ...)
3152
3153   whenever a marked procedure is about to be applied to its arguments.
3154This can help a programmer determine whether a function is being called
3155at the wrong time or with the wrong set of arguments.
3156
3157   In addition, the indentation of the output is useful for
3158demonstrating how the traced applications are or are not tail recursive
3159with respect to each other.  Thus, a trace of a non-tail recursive
3160factorial implementation looks like this:
3161
3162     scheme@(guile-user)> (define (fact1 n)
3163                            (if (zero? n) 1
3164                                (* n (fact1 (1- n)))))
3165     scheme@(guile-user)> ,trace (fact1 4)
3166     trace: (fact1 4)
3167     trace: |  (fact1 3)
3168     trace: |  |  (fact1 2)
3169     trace: |  |  |  (fact1 1)
3170     trace: |  |  |  |  (fact1 0)
3171     trace: |  |  |  |  1
3172     trace: |  |  |  1
3173     trace: |  |  2
3174     trace: |  6
3175     trace: 24
3176
3177   While a typical tail recursive implementation would look more like
3178this:
3179
3180     scheme@(guile-user)> (define (facti acc n)
3181                            (if (zero? n) acc
3182                                (facti (* n acc) (1- n))))
3183     scheme@(guile-user)> (define (fact2 n) (facti 1 n))
3184     scheme@(guile-user)> ,trace (fact2 4)
3185     trace: (fact2 4)
3186     trace: (facti 1 4)
3187     trace: (facti 4 3)
3188     trace: (facti 12 2)
3189     trace: (facti 24 1)
3190     trace: (facti 24 0)
3191     trace: 24
3192
3193   The low-level traps below (*note Low-Level Traps::) share some common
3194options:
3195
3196‘#:width’
3197     The maximum width of trace output.  Trace printouts will try not to
3198     exceed this column, but for highly nested procedure calls, it may
3199     be unavoidable.  Defaults to 80.
3200‘#:vm’
3201     The VM on which to add the traps.  Defaults to the current thread’s
3202     VM.
3203‘#:prefix’
3204     A string to print out before each trace line.  As seen above in the
3205     examples, defaults to ‘"trace: "’.
3206
3207   To have access to these procedures, you’ll need to have imported the
3208‘(system vm trace)’ module:
3209
3210     (use-modules (system vm trace))
3211
3212 -- Scheme Procedure: trace-calls-to-procedure proc [#:width] [#:vm]
3213          [#:prefix]
3214     Print a trace at applications of and returns from PROC.
3215
3216 -- Scheme Procedure: trace-calls-in-procedure proc [#:width] [#:vm]
3217          [#:prefix]
3218     Print a trace at all applications and returns within the dynamic
3219     extent of calls to PROC.
3220
3221 -- Scheme Procedure: trace-instructions-in-procedure proc [#:width]
3222          [#:vm]
3223     Print a trace at all instructions executed in the dynamic extent of
3224     calls to PROC.
3225
3226   In addition, Guile defines a procedure to call a thunk, tracing all
3227procedure calls and returns within the thunk.
3228
3229 -- Scheme Procedure: call-with-trace thunk [#:calls?=#t]
3230          [#:instructions?=#f] [#:width=80]
3231     Call THUNK, tracing all execution within its dynamic extent.
3232
3233     If CALLS? is true, Guile will print a brief report at each
3234     procedure call and return, as given above.
3235
3236     If INSTRUCTIONS? is true, Guile will also print a message each time
3237     an instruction is executed.  This is a lot of output, but it is
3238     sometimes useful when doing low-level optimization.
3239
3240     Note that because this procedure manipulates the VM trace level
3241     directly, it doesn’t compose well with traps at the REPL.
3242
3243   *Note Profile Commands::, for more information on tracing at the
3244REPL.
3245
3246
3247File: guile.info,  Node: Trap States,  Next: High-Level Traps,  Prev: Tracing Traps,  Up: Traps
3248
32496.26.4.5 Trap States
3250....................
3251
3252When multiple traps are present in a system, we begin to have a
3253bookkeeping problem.  How are they named?  How does one disable, enable,
3254or delete them?
3255
3256   Guile’s answer to this is to keep an implicit per-thread “trap
3257state”.  The trap state object is not exposed to the user; rather, API
3258that works on trap states fetches the current trap state from the
3259dynamic environment.
3260
3261   Traps are identified by integers.  A trap can be enabled, disabled,
3262or removed, and can have an associated user-visible name.
3263
3264   These procedures have their own module:
3265
3266     (use-modules (system vm trap-state))
3267
3268 -- Scheme Procedure: add-trap! trap name
3269     Add a trap to the current trap state, associating the given NAME
3270     with it.  Returns a fresh trap identifier (an integer).
3271
3272     Note that usually the more specific functions detailed in *note
3273     High-Level Traps:: are used in preference to this one.
3274
3275 -- Scheme Procedure: list-traps
3276     List the current set of traps, both enabled and disabled.  Returns
3277     a list of integers.
3278
3279 -- Scheme Procedure: trap-name idx
3280     Returns the name associated with trap IDX, or ‘#f’ if there is no
3281     such trap.
3282
3283 -- Scheme Procedure: trap-enabled? idx
3284     Returns ‘#t’ if trap IDX is present and enabled, or ‘#f’ otherwise.
3285
3286 -- Scheme Procedure: enable-trap! idx
3287     Enables trap IDX.
3288
3289 -- Scheme Procedure: disable-trap! idx
3290     Disables trap IDX.
3291
3292 -- Scheme Procedure: delete-trap! idx
3293     Removes trap IDX, disabling it first, if necessary.
3294
3295
3296File: guile.info,  Node: High-Level Traps,  Prev: Trap States,  Up: Traps
3297
32986.26.4.6 High-Level Traps
3299.........................
3300
3301The low-level trap API allows one to make traps that call procedures,
3302and the trap state API allows one to keep track of what traps are there.
3303But neither of these APIs directly helps you when you want to set a
3304breakpoint, because it’s unclear what to do when the trap fires.  Do you
3305enter a debugger, or mail a summary of the situation to your great-aunt,
3306or what?
3307
3308   So for the common case in which you just want to install breakpoints,
3309and then have them all result in calls to one parameterizable procedure,
3310we have the high-level trap interface.
3311
3312   Perhaps we should have started this section with this interface, as
3313it’s clearly the one most people should use.  But as its capabilities
3314and limitations proceed from the lower layers, we felt that the
3315character-building exercise of building a mental model might be helpful.
3316
3317   These procedures share a module with trap states:
3318
3319     (use-modules (system vm trap-state))
3320
3321 -- Scheme Procedure: with-default-trap-handler handler thunk
3322     Call THUNK in a dynamic context in which HANDLER is the current
3323     trap handler.
3324
3325     Additionally, during the execution of THUNK, the VM trace level
3326     (*note VM Hooks::) is set to the number of enabled traps.  This
3327     ensures that traps will in fact fire.
3328
3329     HANDLER may be ‘#f’, in which case VM hooks are not enabled as they
3330     otherwise would be, as there is nothing to handle the traps.
3331
3332   The trace-level-setting behavior of ‘with-default-trap-handler’ is
3333one of its more useful aspects, but if you are willing to forgo that,
3334and just want to install a global trap handler, there’s a function for
3335that too:
3336
3337 -- Scheme Procedure: install-trap-handler! handler
3338     Set the current thread’s trap handler to HANDLER.
3339
3340   Trap handlers are called when traps installed by procedures from this
3341module fire.  The current “consumer” of this API is Guile’s REPL, but
3342one might easily imagine other trap handlers being used to integrate
3343with other debugging tools.
3344
3345 -- Scheme Procedure: add-trap-at-procedure-call! proc
3346     Install a trap that will fire when PROC is called.
3347
3348     This is a breakpoint.
3349
3350 -- Scheme Procedure: add-trace-at-procedure-call! proc
3351     Install a trap that will print a tracing message when PROC is
3352     called.  *Note Tracing Traps::, for more information.
3353
3354     This is a tracepoint.
3355
3356 -- Scheme Procedure: add-trap-at-source-location! file user-line
3357     Install a trap that will fire when control reaches the given source
3358     location.  USER-LINE is one-indexed, as users count lines, instead
3359     of zero-indexed, as Guile counts lines.
3360
3361     This is a source breakpoint.
3362
3363 -- Scheme Procedure: add-ephemeral-trap-at-frame-finish! frame handler
3364     Install a trap that will call HANDLER when FRAME finishes
3365     executing.  The trap will be removed from the trap state after
3366     firing, or on nonlocal exit.
3367
3368     This is a finish trap, used to implement the “finish” REPL command.
3369
3370 -- Scheme Procedure: add-ephemeral-stepping-trap! frame handler
3371          [#:into?] [#:instruction?]
3372     Install a trap that will call HANDLER after stepping to a different
3373     source line or instruction.  The trap will be removed from the trap
3374     state after firing, or on nonlocal exit.
3375
3376     If INSTRUCTION? is false (the default), the trap will fire when
3377     control reaches a new source line.  Otherwise it will fire when
3378     control reaches a new instruction.
3379
3380     Additionally, if INTO? is false (not the default), the trap will
3381     only fire for frames at or prior to the given frame.  If INTO? is
3382     true (the default), the trap may step into nested procedure
3383     invocations.
3384
3385     This is a stepping trap, used to implement the “step”, “next”,
3386     “step-instruction”, and “next-instruction” REPL commands.
3387
3388
3389File: guile.info,  Node: GDB Support,  Prev: Traps,  Up: Debugging
3390
33916.26.5 GDB Support
3392------------------
3393
3394Sometimes, you may find it necessary to debug Guile applications at the
3395C level.  Doing so can be tedious, in particular because the debugger is
3396oblivious to Guile’s ‘SCM’ type, and thus unable to display ‘SCM’ values
3397in any meaningful way:
3398
3399     (gdb) frame
3400     #0  scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
3401
3402   To address that, Guile comes with an extension of the GNU Debugger
3403(GDB) that contains a “pretty-printer” for ‘SCM’ values.  With this GDB
3404extension, the C frame in the example above shows up like this:
3405
3406     (gdb) frame
3407     #0  scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
3408
3409Here GDB was able to decode the list pointed to by OBJ, and to print it
3410using Scheme’s read syntax.
3411
3412   That extension is a ‘.scm’ file installed alongside the ‘libguile’
3413shared library.  When GDB 7.8 or later is installed and compiled with
3414support for extensions written in Guile, the extension is automatically
3415loaded when debugging a program linked against ‘libguile’ (*note
3416(gdb)Auto-loading::).  Note that the directory where ‘libguile’ is
3417installed must be among GDB’s auto-loading “safe directories” (*note
3418(gdb)Auto-loading safe path::).
3419
3420
3421File: guile.info,  Node: Code Coverage,  Prev: Debugging,  Up: API Reference
3422
34236.27 Code Coverage Reports
3424==========================
3425
3426When writing a test suite for a program or library, it is desirable to
3427know what part of the code is “covered” by the test suite.  The ‘(system
3428vm coverage)’ module provides tools to gather code coverage data and to
3429present them, as detailed below.
3430
3431 -- Scheme Procedure: with-code-coverage thunk
3432     Run THUNK, a zero-argument procedure, while instrumenting Guile’s
3433     virtual machine to collect code coverage data.  Return code
3434     coverage data and the values returned by THUNK.
3435
3436 -- Scheme Procedure: coverage-data? obj
3437     Return ‘#t’ if OBJ is a “coverage data” object as returned by
3438     ‘with-code-coverage’.
3439
3440 -- Scheme Procedure: coverage-data->lcov data port #:key modules
3441     Traverse code coverage information DATA, as obtained with
3442     ‘with-code-coverage’, and write coverage information to port in the
3443     ‘.info’ format used by LCOV
3444     (http://ltp.sourceforge.net/coverage/lcov.php).  The report will
3445     include all of MODULES (or, by default, all the currently loaded
3446     modules) even if their code was not executed.
3447
3448     The generated data can be fed to LCOV’s ‘genhtml’ command to
3449     produce an HTML report, which aids coverage data visualization.
3450
3451   Here’s an example use:
3452
3453     (use-modules (system vm coverage)
3454                  (system vm vm))
3455
3456     (call-with-values (lambda ()
3457                         (with-code-coverage
3458                           (lambda ()
3459                             (do-something-tricky))))
3460       (lambda (data result)
3461         (let ((port (open-output-file "lcov.info")))
3462           (coverage-data->lcov data port)
3463           (close file))))
3464
3465   In addition, the module provides low-level procedures that would make
3466it possible to write other user interfaces to the coverage data.
3467
3468 -- Scheme Procedures: instrumented-source-files data
3469     Return the list of “instrumented” source files, i.e., source files
3470     whose code was loaded at the time DATA was collected.
3471
3472 -- Scheme Procedures: line-execution-counts data file
3473     Return a list of line number/execution count pairs for FILE, or
3474     ‘#f’ if FILE is not among the files covered by DATA.  This includes
3475     lines with zero count.
3476
3477 -- Scheme Procedures: instrumented/executed-lines data file
3478     Return the number of instrumented and the number of executed source
3479     lines in FILE according to DATA.
3480
3481 -- Scheme Procedures: procedure-execution-count data proc
3482     Return the number of times PROC’s code was executed, according to
3483     DATA, or ‘#f’ if PROC was not executed.  When PROC is a closure,
3484     the number of times its code was executed is returned, not the
3485     number of times this code associated with this particular closure
3486     was executed.
3487
3488
3489File: guile.info,  Node: Guile Modules,  Next: GOOPS,  Prev: API Reference,  Up: Top
3490
34917 Guile Modules
3492***************
3493
3494* Menu:
3495
3496* SLIB::                        Using the SLIB Scheme library.
3497* POSIX::                       POSIX system calls and networking.
3498* Web::                         HTTP, the web, and all that.
3499* getopt-long::                 Command line handling.
3500* SRFI Support::                Support for various SRFIs.
3501* R6RS Support::                Modules defined by the R6RS.
3502* R7RS Support::                Modules defined by the R7RS.
3503* Pattern Matching::            Generic pattern matching constructs.
3504* Readline Support::            Module for using the readline library.
3505* Pretty Printing::             Nicely formatting Scheme objects for output.
3506* Formatted Output::            The ‘format’ procedure.
3507* File Tree Walk::              Traversing the file system.
3508* Queues::                      First-in first-out queuing.
3509* Streams::                     Sequences of values.
3510* Buffered Input::              Ports made from a reader function.
3511* Expect::			Controlling interactive programs with Guile.
3512* sxml-match::                  Pattern matching of SXML.
3513* The Scheme shell (scsh)::     Using scsh interfaces in Guile.
3514* Curried Definitions::         Extended ‘define’ syntax.
3515* Statprof::                    An easy-to-use statistical profiler.
3516* SXML::                        Parsing, transforming, and serializing XML.
3517* Texinfo Processing::          Munging documents written in Texinfo.
3518
3519
3520File: guile.info,  Node: SLIB,  Next: POSIX,  Up: Guile Modules
3521
35227.1 SLIB
3523========
3524
3525SLIB is a portable library of Scheme packages which can be used with
3526Guile and other Scheme implementations.  SLIB is not included in the
3527Guile distribution, but can be installed separately (*note SLIB
3528installation::).  It is available from
3529<http://people.csail.mit.edu/jaffer/SLIB.html>.
3530
3531   After SLIB is installed, the following Scheme expression must be
3532executed before the SLIB facilities can be used:
3533
3534     (use-modules (ice-9 slib))
3535
3536‘require’ can then be used in the usual way (*note (slib)Require::).
3537For example,
3538
3539     (use-modules (ice-9 slib))
3540     (require 'primes)
3541     (prime? 13)
3542     ⇒ #t
3543
3544   A few Guile core functions are overridden by the SLIB setups; for
3545example the SLIB version of ‘delete-file’ returns a boolean indicating
3546success or failure, whereas the Guile core version throws an error for
3547failure.  In general (and as might be expected) when SLIB is loaded it’s
3548the SLIB specifications that are followed.
3549
3550* Menu:
3551
3552* SLIB installation::
3553* JACAL::
3554
3555
3556File: guile.info,  Node: SLIB installation,  Next: JACAL,  Up: SLIB
3557
35587.1.1 SLIB installation
3559-----------------------
3560
3561The following procedure works, e.g., with SLIB version 3a3 (*note SLIB
3562installation: (slib)Installation.):
3563
3564  1. Unpack SLIB and install it using ‘make install’ from its directory.
3565     By default, this will install SLIB in ‘/usr/local/lib/slib/’.
3566     Running ‘make install-info’ installs its documentation, by default
3567     under ‘/usr/local/info/’.
3568
3569  2. Define the ‘SCHEME_LIBRARY_PATH’ environment variable:
3570
3571          $ SCHEME_LIBRARY_PATH=/usr/local/lib/slib/
3572          $ export SCHEME_LIBRARY_PATH
3573
3574     Alternatively, you can create a symlink in the Guile directory to
3575     SLIB, e.g.:
3576
3577          ln -s /usr/local/lib/slib /usr/local/share/guile/3.0/slib
3578
3579  3. Use Guile to create the catalog file, e.g.,:
3580
3581          # guile
3582          guile> (use-modules (ice-9 slib))
3583          guile> (require 'new-catalog)
3584          guile> (quit)
3585
3586     The catalog data should now be in
3587/usr/local/share/guile/3.0/slibcat’.
3588
3589     If instead you get an error such as:
3590
3591          Unbound variable: scheme-implementation-type
3592
3593     then a solution is to get a newer version of Guile, or to modify
3594ice-9/slib.scm’ to use ‘define-public’ for the offending
3595     variables.
3596
3597
3598File: guile.info,  Node: JACAL,  Prev: SLIB installation,  Up: SLIB
3599
36007.1.2 JACAL
3601-----------
3602
3603Jacal is a symbolic math package written in Scheme by Aubrey Jaffer.  It
3604is usually installed as an extra package in SLIB.
3605
3606   You can use Guile’s interface to SLIB to invoke Jacal:
3607
3608     (use-modules (ice-9 slib))
3609     (slib:load "math")
3610     (math)
3611
3612For complete documentation on Jacal, please read the Jacal manual.  If
3613it has been installed on line, you can look at *note Jacal: (jacal)Top.
3614Otherwise you can find it on the web at
3615<http://www-swiss.ai.mit.edu/~jaffer/JACAL.html>
3616
3617
3618File: guile.info,  Node: POSIX,  Next: Web,  Prev: SLIB,  Up: Guile Modules
3619
36207.2 POSIX System Calls and Networking
3621=====================================
3622
3623* Menu:
3624
3625* Conventions::                 Conventions employed by the POSIX interface.
3626* Ports and File Descriptors::  Scheme “ports” and Unix file descriptors
3627                                  have different representations.
3628* File System::                 stat, chown, chmod, etc.
3629* User Information::            Retrieving a user’s GECOS (/etc/passwd) entry.
3630* Time::                        gettimeofday, localtime, strftime, etc.
3631* Runtime Environment::         Accessing and modifying Guile’s environment.
3632* Processes::                   getuid, getpid, etc.
3633* Signals::                     sigaction, kill, pause, alarm, setitimer, etc.
3634* Terminals and Ptys::          ttyname, tcsetpgrp, etc.
3635* Pipes::                       Communicating data between processes.
3636* Networking::                  gethostbyaddr, getnetent, socket, bind, listen.
3637* System Identification::       Obtaining information about the system.
3638* Locales::                     setlocale, etc.
3639* Encryption::
3640
3641
3642File: guile.info,  Node: Conventions,  Next: Ports and File Descriptors,  Up: POSIX
3643
36447.2.1 POSIX Interface Conventions
3645---------------------------------
3646
3647These interfaces provide access to operating system facilities.  They
3648provide a simple wrapping around the underlying C interfaces to make
3649usage from Scheme more convenient.  They are also used to implement the
3650Guile port of scsh (*note The Scheme shell (scsh)::).
3651
3652   Generally there is a single procedure for each corresponding Unix
3653facility.  There are some exceptions, such as procedures implemented for
3654speed and convenience in Scheme with no primitive Unix equivalent, e.g.
3655‘copy-file’.
3656
3657   The interfaces are intended as far as possible to be portable across
3658different versions of Unix.  In some cases procedures which can’t be
3659implemented on particular systems may become no-ops, or perform limited
3660actions.  In other cases they may throw errors.
3661
3662   General naming conventions are as follows:
3663
3664   • The Scheme name is often identical to the name of the underlying
3665     Unix facility.
3666   • Underscores in Unix procedure names are converted to hyphens.
3667   • Procedures which destructively modify Scheme data have exclamation
3668     marks appended, e.g., ‘recv!’.
3669   • Predicates (returning only ‘#t’ or ‘#f’) have question marks
3670     appended, e.g., ‘access?’.
3671   • Some names are changed to avoid conflict with dissimilar interfaces
3672     defined by scsh, e.g., ‘primitive-fork’.
3673   • Unix preprocessor names such as ‘EPERM’ or ‘R_OK’ are converted to
3674     Scheme variables of the same name (underscores are not replaced
3675     with hyphens).
3676
3677   Unexpected conditions are generally handled by raising exceptions.
3678There are a few procedures which return a special value if they don’t
3679succeed, e.g., ‘getenv’ returns ‘#f’ if it the requested string is not
3680found in the environment.  These cases are noted in the documentation.
3681
3682   For ways to deal with exceptions, see *note Exceptions::.
3683
3684   Errors which the C library would report by returning a null pointer
3685or through some other means are reported by raising a ‘system-error’
3686exception with ‘scm-error’ (*note Error Reporting::).  The DATA
3687parameter is a list containing the Unix ‘errno’ value (an integer).  For
3688example,
3689
3690     (define (my-handler key func fmt fmtargs data)
3691       (display key) (newline)
3692       (display func) (newline)
3693       (apply format #t fmt fmtargs) (newline)
3694       (display data) (newline))
3695
3696     (catch 'system-error
3697       (lambda () (dup2 -123 -456))
3698       my-handler)
3699
37003701     system-error
3702     dup2
3703     Bad file descriptor
3704     (9)
3705
3706
3707 -- Function: system-error-errno arglist
3708     Return the ‘errno’ value from a list which is the arguments to an
3709     exception handler.  If the exception is not a ‘system-error’, then
3710     the return is ‘#f’.  For example,
3711
3712          (catch
3713           'system-error
3714           (lambda ()
3715             (mkdir "/this-ought-to-fail-if-I'm-not-root"))
3716           (lambda stuff
3717             (let ((errno (system-error-errno stuff)))
3718               (cond
3719                ((= errno EACCES)
3720                 (display "You're not allowed to do that."))
3721                ((= errno EEXIST)
3722                 (display "Already exists."))
3723                (#t
3724                 (display (strerror errno))))
3725               (newline))))
3726
3727
3728File: guile.info,  Node: Ports and File Descriptors,  Next: File System,  Prev: Conventions,  Up: POSIX
3729
37307.2.2 Ports and File Descriptors
3731--------------------------------
3732
3733Conventions generally follow those of scsh, *note The Scheme shell
3734(scsh)::.
3735
3736   Each open file port has an associated operating system file
3737descriptor.  File descriptors are generally not useful in Scheme
3738programs; however they may be needed when interfacing with foreign code
3739and the Unix environment.
3740
3741   A file descriptor can be extracted from a port and a new port can be
3742created from a file descriptor.  However a file descriptor is just an
3743integer and the garbage collector doesn’t recognize it as a reference to
3744the port.  If all other references to the port were dropped, then it’s
3745likely that the garbage collector would free the port, with the
3746side-effect of closing the file descriptor prematurely.
3747
3748   To assist the programmer in avoiding this problem, each port has an
3749associated “revealed count” which can be used to keep track of how many
3750times the underlying file descriptor has been stored in other places.
3751If a port’s revealed count is greater than zero, the file descriptor
3752will not be closed when the port is garbage collected.  A programmer can
3753therefore ensure that the revealed count will be greater than zero if
3754the file descriptor is needed elsewhere.
3755
3756   For the simple case where a file descriptor is “imported” once to
3757become a port, it does not matter if the file descriptor is closed when
3758the port is garbage collected.  There is no need to maintain a revealed
3759count.  Likewise when “exporting” a file descriptor to the external
3760environment, setting the revealed count is not required provided the
3761port is kept open (i.e., is pointed to by a live Scheme binding) while
3762the file descriptor is in use.
3763
3764   To correspond with traditional Unix behaviour, three file descriptors
3765(0, 1, and 2) are automatically imported when a program starts up and
3766assigned to the initial values of the current/standard input, output,
3767and error ports, respectively.  The revealed count for each is initially
3768set to one, so that dropping references to one of these ports will not
3769result in its garbage collection: it could be retrieved with ‘fdopen’ or
3770‘fdes->ports’.
3771
3772   Guile’s ports can be buffered.  This means that writing a byte to a
3773file port goes to the internal buffer first, and only when the buffer is
3774full (or the user invokes ‘force-output’ on the port) is the data
3775actually written to the file descriptor.  Likewise on input, bytes are
3776read in from the file descriptor in blocks and placed in a buffer.
3777Reading a character via ‘read-char’ first goes to the buffer, filling it
3778as needed.  Usually read buffering is more or less transparent, but
3779write buffering can sometimes cause writes to be delayed unexpectedly,
3780if you forget to call ‘force-output’.  *Note Buffering::, for more on
3781how to control port buffers.
3782
3783   Note however that some procedures (e.g., ‘recv!’) will accept ports
3784as arguments, but will actually operate directly on the file descriptor
3785underlying the port.  Any port buffering is ignored, including the
3786buffer which implements ‘peek-char’ and ‘unread-char’.
3787
3788 -- Scheme Procedure: port-revealed port
3789 -- C Function: scm_port_revealed (port)
3790     Return the revealed count for PORT.
3791
3792 -- Scheme Procedure: set-port-revealed! port rcount
3793 -- C Function: scm_set_port_revealed_x (port, rcount)
3794     Sets the revealed count for a PORT to RCOUNT.  The return value is
3795     unspecified.
3796
3797 -- Scheme Procedure: fileno port
3798 -- C Function: scm_fileno (port)
3799     Return the integer file descriptor underlying PORT.  Does not
3800     change its revealed count.
3801
3802 -- Scheme Procedure: port->fdes port
3803     Returns the integer file descriptor underlying PORT.  As a side
3804     effect the revealed count of PORT is incremented.
3805
3806 -- Scheme Procedure: fdopen fdes modes
3807 -- C Function: scm_fdopen (fdes, modes)
3808     Return a new port based on the file descriptor FDES.  Modes are
3809     given by the string MODES.  The revealed count of the port is
3810     initialized to zero.  The MODES string is the same as that accepted
3811     by ‘open-file’ (*note open-file: File Ports.).
3812
3813 -- Scheme Procedure: fdes->ports fdes
3814 -- C Function: scm_fdes_to_ports (fdes)
3815     Return a list of existing ports which have FDES as an underlying
3816     file descriptor, without changing their revealed counts.
3817
3818 -- Scheme Procedure: fdes->inport fdes
3819     Returns an existing input port which has FDES as its underlying
3820     file descriptor, if one exists, and increments its revealed count.
3821     Otherwise, returns a new input port with a revealed count of 1.
3822
3823 -- Scheme Procedure: fdes->outport fdes
3824     Returns an existing output port which has FDES as its underlying
3825     file descriptor, if one exists, and increments its revealed count.
3826     Otherwise, returns a new output port with a revealed count of 1.
3827
3828 -- Scheme Procedure: primitive-move->fdes port fdes
3829 -- C Function: scm_primitive_move_to_fdes (port, fdes)
3830     Moves the underlying file descriptor for PORT to the integer value
3831     FDES without changing the revealed count of PORT.  Any other ports
3832     already using this descriptor will be automatically shifted to new
3833     descriptors and their revealed counts reset to zero.  The return
3834     value is ‘#f’ if the file descriptor already had the required value
3835     or ‘#t’ if it was moved.
3836
3837 -- Scheme Procedure: move->fdes port fdes
3838     Moves the underlying file descriptor for PORT to the integer value
3839     FDES and sets its revealed count to one.  Any other ports already
3840     using this descriptor will be automatically shifted to new
3841     descriptors and their revealed counts reset to zero.  The return
3842     value is unspecified.
3843
3844 -- Scheme Procedure: release-port-handle port
3845     Decrements the revealed count for a port.
3846
3847 -- Scheme Procedure: fsync port_or_fd
3848 -- C Function: scm_fsync (port_or_fd)
3849     Copies any unwritten data for the specified output file descriptor
3850     to disk.  If PORT_OR_FD is a port, its buffer is flushed before the
3851     underlying file descriptor is fsync’d.  The return value is
3852     unspecified.
3853
3854 -- Scheme Procedure: open path flags [mode]
3855 -- C Function: scm_open (path, flags, mode)
3856     Open the file named by PATH for reading and/or writing.  FLAGS is
3857     an integer specifying how the file should be opened.  MODE is an
3858     integer specifying the permission bits of the file, if it needs to
3859     be created, before the umask (*note Processes::) is applied.  The
3860     default is 666 (Unix itself has no default).
3861
3862     FLAGS can be constructed by combining variables using ‘logior’.
3863     Basic flags are:
3864
3865      -- Variable: O_RDONLY
3866          Open the file read-only.
3867      -- Variable: O_WRONLY
3868          Open the file write-only.
3869      -- Variable: O_RDWR
3870          Open the file read/write.
3871      -- Variable: O_APPEND
3872          Append to the file instead of truncating.
3873      -- Variable: O_CREAT
3874          Create the file if it does not already exist.
3875
3876     *Note (libc)File Status Flags::, for additional flags.
3877
3878 -- Scheme Procedure: open-fdes path flags [mode]
3879 -- C Function: scm_open_fdes (path, flags, mode)
3880     Similar to ‘open’ but return a file descriptor instead of a port.
3881
3882 -- Scheme Procedure: close fd_or_port
3883 -- C Function: scm_close (fd_or_port)
3884     Similar to ‘close-port’ (*note close-port: Ports.), but also works
3885     on file descriptors.  A side effect of closing a file descriptor is
3886     that any ports using that file descriptor are moved to a different
3887     file descriptor and have their revealed counts set to zero.
3888
3889 -- Scheme Procedure: close-fdes fd
3890 -- C Function: scm_close_fdes (fd)
3891     A simple wrapper for the ‘close’ system call.  Close file
3892     descriptor FD, which must be an integer.  Unlike ‘close’, the file
3893     descriptor will be closed even if a port is using it.  The return
3894     value is unspecified.
3895
3896 -- Scheme Procedure: pipe
3897 -- C Function: scm_pipe ()
3898     Return a newly created pipe: a pair of ports which are linked
3899     together on the local machine.  The CAR is the input port and the
3900     CDR is the output port.  Data written (and flushed) to the output
3901     port can be read from the input port.  Pipes are commonly used for
3902     communication with a newly forked child process.  The need to flush
3903     the output port can be avoided by making it unbuffered using
3904     ‘setvbuf’ (*note Buffering::).
3905
3906      -- Variable: PIPE_BUF
3907          A write of up to ‘PIPE_BUF’ many bytes to a pipe is atomic,
3908          meaning when done it goes into the pipe instantaneously and as
3909          a contiguous block (*note Atomicity of Pipe I/O: (libc)Pipe
3910          Atomicity.).
3911
3912     Note that the output port is likely to block if too much data has
3913     been written but not yet read from the input port.  Typically the
3914     capacity is ‘PIPE_BUF’ bytes.
3915
3916   The next group of procedures perform a ‘dup2’ system call, if NEWFD
3917(an integer) is supplied, otherwise a ‘dup’.  The file descriptor to be
3918duplicated can be supplied as an integer or contained in a port.  The
3919type of value returned varies depending on which procedure is used.
3920
3921   All procedures also have the side effect when performing ‘dup2’ that
3922any ports using NEWFD are moved to a different file descriptor and have
3923their revealed counts set to zero.
3924
3925 -- Scheme Procedure: dup->fdes fd_or_port [fd]
3926 -- C Function: scm_dup_to_fdes (fd_or_port, fd)
3927     Return a new integer file descriptor referring to the open file
3928     designated by FD_OR_PORT, which must be either an open file port or
3929     a file descriptor.
3930
3931 -- Scheme Procedure: dup->inport port/fd [newfd]
3932     Returns a new input port using the new file descriptor.
3933
3934 -- Scheme Procedure: dup->outport port/fd [newfd]
3935     Returns a new output port using the new file descriptor.
3936
3937 -- Scheme Procedure: dup port/fd [newfd]
3938     Returns a new port if PORT/FD is a port, with the same mode as the
3939     supplied port, otherwise returns an integer file descriptor.
3940
3941 -- Scheme Procedure: dup->port port/fd mode [newfd]
3942     Returns a new port using the new file descriptor.  MODE supplies a
3943     mode string for the port (*note open-file: File Ports.).
3944
3945 -- Scheme Procedure: duplicate-port port modes
3946     Returns a new port which is opened on a duplicate of the file
3947     descriptor underlying PORT, with mode string MODES as for *note
3948     open-file: File Ports.  The two ports will share a file position
3949     and file status flags.
3950
3951     Unexpected behaviour can result if both ports are subsequently used
3952     and the original and/or duplicate ports are buffered.  The mode
3953     string can include ‘0’ to obtain an unbuffered duplicate port.
3954
3955     This procedure is equivalent to ‘(dup->port PORT MODES)’.
3956
3957 -- Scheme Procedure: redirect-port old_port new_port
3958 -- C Function: scm_redirect_port (old_port, new_port)
3959     This procedure takes two ports and duplicates the underlying file
3960     descriptor from OLD_PORT into NEW_PORT.  The current file
3961     descriptor in NEW_PORT will be closed.  After the redirection the
3962     two ports will share a file position and file status flags.
3963
3964     The return value is unspecified.
3965
3966     Unexpected behaviour can result if both ports are subsequently used
3967     and the original and/or duplicate ports are buffered.
3968
3969     This procedure does not have any side effects on other ports or
3970     revealed counts.
3971
3972 -- Scheme Procedure: dup2 oldfd newfd
3973 -- C Function: scm_dup2 (oldfd, newfd)
3974     A simple wrapper for the ‘dup2’ system call.  Copies the file
3975     descriptor OLDFD to descriptor number NEWFD, replacing the previous
3976     meaning of NEWFD.  Both OLDFD and NEWFD must be integers.  Unlike
3977     for ‘dup->fdes’ or ‘primitive-move->fdes’, no attempt is made to
3978     move away ports which are using NEWFD.  The return value is
3979     unspecified.
3980
3981 -- Scheme Procedure: port-for-each proc
3982 -- C Function: scm_port_for_each (SCM proc)
3983 -- C Function: scm_c_port_for_each (void (*proc)(void *, SCM), void
3984          *data)
3985     Apply PROC to each port in the Guile port table (FIXME: what is the
3986     Guile port table?)  in turn.  The return value is unspecified.
3987     More specifically, PROC is applied exactly once to every port that
3988     exists in the system at the time ‘port-for-each’ is invoked.
3989     Changes to the port table while ‘port-for-each’ is running have no
3990     effect as far as ‘port-for-each’ is concerned.
3991
3992     The C function ‘scm_port_for_each’ takes a Scheme procedure encoded
3993     as a ‘SCM’ value, while ‘scm_c_port_for_each’ takes a pointer to a
3994     C function and passes along a arbitrary DATA cookie.
3995
3996 -- Scheme Procedure: fcntl port/fd cmd [value]
3997 -- C Function: scm_fcntl (object, cmd, value)
3998     Apply CMD on PORT/FD, either a port or file descriptor.  The VALUE
3999     argument is used by the ‘SET’ commands described below, it’s an
4000     integer value.
4001
4002     Values for CMD are:
4003
4004      -- Variable: F_DUPFD
4005          Duplicate the file descriptor, the same as ‘dup->fdes’ above
4006          does.
4007
4008      -- Variable: F_GETFD
4009      -- Variable: F_SETFD
4010          Get or set flags associated with the file descriptor.  The
4011          only flag is the following,
4012
4013           -- Variable: FD_CLOEXEC
4014               “Close on exec”, meaning the file descriptor will be
4015               closed on an ‘exec’ call (a successful such call).  For
4016               example to set that flag,
4017
4018                    (fcntl port F_SETFD FD_CLOEXEC)
4019
4020               Or better, set it but leave any other possible future
4021               flags unchanged,
4022
4023                    (fcntl port F_SETFD (logior FD_CLOEXEC
4024                                                (fcntl port F_GETFD)))
4025
4026      -- Variable: F_GETFL
4027      -- Variable: F_SETFL
4028          Get or set flags associated with the open file.  These flags
4029          are ‘O_RDONLY’ etc described under ‘open’ above.
4030
4031          A common use is to set ‘O_NONBLOCK’ on a network socket.  The
4032          following sets that flag, and leaves other flags unchanged.
4033
4034               (fcntl sock F_SETFL (logior O_NONBLOCK
4035                                           (fcntl sock F_GETFL)))
4036
4037      -- Variable: F_GETOWN
4038      -- Variable: F_SETOWN
4039          Get or set the process ID of a socket’s owner, for ‘SIGIO’
4040          signals.
4041
4042 -- Scheme Procedure: flock file operation
4043 -- C Function: scm_flock (file, operation)
4044     Apply or remove an advisory lock on an open file.  OPERATION
4045     specifies the action to be done:
4046
4047      -- Variable: LOCK_SH
4048          Shared lock.  More than one process may hold a shared lock for
4049          a given file at a given time.
4050      -- Variable: LOCK_EX
4051          Exclusive lock.  Only one process may hold an exclusive lock
4052          for a given file at a given time.
4053      -- Variable: LOCK_UN
4054          Unlock the file.
4055      -- Variable: LOCK_NB
4056          Don’t block when locking.  This is combined with one of the
4057          other operations using ‘logior’ (*note Bitwise Operations::).
4058          If ‘flock’ would block an ‘EWOULDBLOCK’ error is thrown (*note
4059          Conventions::).
4060
4061     The return value is not specified.  FILE may be an open file
4062     descriptor or an open file descriptor port.
4063
4064     Note that ‘flock’ does not lock files across NFS.
4065
4066 -- Scheme Procedure: select reads writes excepts [secs [usecs]]
4067 -- C Function: scm_select (reads, writes, excepts, secs, usecs)
4068     This procedure has a variety of uses: waiting for the ability to
4069     provide input, accept output, or the existence of exceptional
4070     conditions on a collection of ports or file descriptors, or waiting
4071     for a timeout to occur.
4072
4073     When an error occurs, this procedure throws a ‘system-error’
4074     exception (*note ‘system-error’: Conventions.).  Note that ‘select’
4075     may return early for other reasons, for example due to pending
4076     interrupts.  *Note Asyncs::, for more on interrupts.
4077
4078     READS, WRITES and EXCEPTS can be lists or vectors, with each member
4079     a port or a file descriptor.  The value returned is a list of three
4080     corresponding lists or vectors containing only the members which
4081     meet the specified requirement.  The ability of port buffers to
4082     provide input or accept output is taken into account.  Ordering of
4083     the input lists or vectors is not preserved.
4084
4085     The optional arguments SECS and USECS specify the timeout.  Either
4086     SECS can be specified alone, as either an integer or a real number,
4087     or both SECS and USECS can be specified as integers, in which case
4088     USECS is an additional timeout expressed in microseconds.  If SECS
4089     is omitted or is ‘#f’ then select will wait for as long as it takes
4090     for one of the other conditions to be satisfied.
4091
4092     The scsh version of ‘select’ differs as follows: Only vectors are
4093     accepted for the first three arguments.  The USECS argument is not
4094     supported.  Multiple values are returned instead of a list.
4095     Duplicates in the input vectors appear only once in output.  An
4096     additional ‘select!’ interface is provided.
4097
4098   While it is sometimes necessary to operate at the level of file
4099descriptors, this is an operation whose correctness can only be
4100considered as part of a whole program.  So for example while the effects
4101of ‘(string-set! x 34 #\y)’ are limited to the bits of code that can
4102access X, ‘(close-fdes 34)’ mutates the state of the entire process.  In
4103particular if another thread is using file descriptor 34 then their
4104state might be corrupted; and another thread which opens a file might
4105cause file descriptor 34 to be re-used, so that corruption could
4106manifest itself in a strange way.
4107
4108   However when working with file descriptors, it’s common to want to
4109associate information with the file descriptor, perhaps in a side table.
4110To support this use case and to allow user code to remove an association
4111when a file descriptor is closed, Guile offers “fdes finalizers”.
4112
4113   As the name indicates, fdes finalizers are finalizers – they can run
4114in response to garbage collection, and they can also run in response to
4115explicit calls to ‘close-port’, ‘close-fdes’, or the like.  As such they
4116inherit many of the pitfalls of finalizers: they may be invoked from
4117concurrent threads, or not at all.  *Note Foreign Object Memory
4118Management::, for more on finalizers.
4119
4120   To use fdes finalizers, import their module;
4121
4122     (use-modules (ice-9 fdes-finalizers))
4123
4124 -- Scheme Procedure: add-fdes-finalizer! fdes finalizer
4125 -- Scheme Procedure: remove-fdes-finalizer! fdes finalizer
4126     Add or remove a finalizer for FDES.  A finalizer is a procedure
4127     that is called by Guile when a file descriptor is closed.  The file
4128     descriptor being closed is passed as the one argument to the
4129     finalizer.  If a finalizer has been added multiple times to a file
4130     descriptor, to remove it would require that number of calls to
4131     ‘remove-fdes-finalizer!’.
4132
4133     The finalizers added to a file descriptor are called by Guile in an
4134     unspecified order, and their return values are ignored.
4135
4136
4137File: guile.info,  Node: File System,  Next: User Information,  Prev: Ports and File Descriptors,  Up: POSIX
4138
41397.2.3 File System
4140-----------------
4141
4142These procedures allow querying and setting file system attributes (such
4143as owner, permissions, sizes and types of files); deleting, copying,
4144renaming and linking files; creating and removing directories and
4145querying their contents; syncing the file system and creating special
4146files.
4147
4148 -- Scheme Procedure: access? path how
4149 -- C Function: scm_access (path, how)
4150     Test accessibility of a file under the real UID and GID of the
4151     calling process.  The return is ‘#t’ if PATH exists and the
4152     permissions requested by HOW are all allowed, or ‘#f’ if not.
4153
4154     HOW is an integer which is one of the following values, or a
4155     bitwise-OR (‘logior’) of multiple values.
4156
4157      -- Variable: R_OK
4158          Test for read permission.
4159      -- Variable: W_OK
4160          Test for write permission.
4161      -- Variable: X_OK
4162          Test for execute permission.
4163      -- Variable: F_OK
4164          Test for existence of the file.  This is implied by each of
4165          the other tests, so there’s no need to combine it with them.
4166
4167     It’s important to note that ‘access?’ does not simply indicate what
4168     will happen on attempting to read or write a file.  In normal
4169     circumstances it does, but in a set-UID or set-GID program it
4170     doesn’t because ‘access?’ tests the real ID, whereas an open or
4171     execute attempt uses the effective ID.
4172
4173     A program which will never run set-UID/GID can ignore the
4174     difference between real and effective IDs, but for maximum
4175     generality, especially in library functions, it’s best not to use
4176     ‘access?’ to predict the result of an open or execute, instead
4177     simply attempt that and catch any exception.
4178
4179     The main use for ‘access?’ is to let a set-UID/GID program
4180     determine what the invoking user would have been allowed to do,
4181     without the greater (or perhaps lesser) privileges afforded by the
4182     effective ID. For more on this, see *note (libc)Testing File
4183     Access::.
4184
4185 -- Scheme Procedure: stat object [exception-on-error?]
4186 -- C Function: scm_stat (object, exception_on_error)
4187     Return an object containing various information about the file
4188     determined by OBJECT.  OBJECT can be a string containing a file
4189     name or a port or integer file descriptor which is open on a file
4190     (in which case ‘fstat’ is used as the underlying system call).
4191
4192     If the optional EXCEPTION_ON_ERROR argument is true, which is the
4193     default, an exception will be raised if the underlying system call
4194     returns an error, for example if the file is not found or is not
4195     readable.  Otherwise, an error will cause ‘stat’ to return ‘#f’.
4196
4197     The object returned by ‘stat’ can be passed as a single parameter
4198     to the following procedures, all of which return integers:
4199
4200      -- Scheme Procedure: stat:dev st
4201          The device number containing the file.
4202      -- Scheme Procedure: stat:ino st
4203          The file serial number, which distinguishes this file from all
4204          other files on the same device.
4205      -- Scheme Procedure: stat:mode st
4206          The mode of the file.  This is an integer which incorporates
4207          file type information and file permission bits.  See also
4208          ‘stat:type’ and ‘stat:perms’ below.
4209      -- Scheme Procedure: stat:nlink st
4210          The number of hard links to the file.
4211      -- Scheme Procedure: stat:uid st
4212          The user ID of the file’s owner.
4213      -- Scheme Procedure: stat:gid st
4214          The group ID of the file.
4215      -- Scheme Procedure: stat:rdev st
4216          Device ID; this entry is defined only for character or block
4217          special files.  On some systems this field is not available at
4218          all, in which case ‘stat:rdev’ returns ‘#f’.
4219      -- Scheme Procedure: stat:size st
4220          The size of a regular file in bytes.
4221      -- Scheme Procedure: stat:atime st
4222          The last access time for the file, in seconds.
4223      -- Scheme Procedure: stat:mtime st
4224          The last modification time for the file, in seconds.
4225      -- Scheme Procedure: stat:ctime st
4226          The last modification time for the attributes of the file, in
4227          seconds.
4228      -- Scheme Procedure: stat:atimensec st
4229      -- Scheme Procedure: stat:mtimensec st
4230      -- Scheme Procedure: stat:ctimensec st
4231          The fractional part of a file’s access, modification, or
4232          attribute modification time, in nanoseconds.  Nanosecond
4233          timestamps are only available on some operating systems and
4234          file systems.  If Guile cannot retrieve nanosecond-level
4235          timestamps for a file, these fields will be set to 0.
4236      -- Scheme Procedure: stat:blksize st
4237          The optimal block size for reading or writing the file, in
4238          bytes.  On some systems this field is not available, in which
4239          case ‘stat:blksize’ returns a sensible suggested block size.
4240      -- Scheme Procedure: stat:blocks st
4241          The amount of disk space that the file occupies measured in
4242          units of 512 byte blocks.  On some systems this field is not
4243          available, in which case ‘stat:blocks’ returns ‘#f’.
4244
4245     In addition, the following procedures return the information from
4246     ‘stat:mode’ in a more convenient form:
4247
4248      -- Scheme Procedure: stat:type st
4249          A symbol representing the type of file.  Possible values are
4250          ‘regular’, ‘directory’, ‘symlink’, ‘block-special’,
4251          ‘char-special’, ‘fifo’, ‘socket’, and ‘unknown’.
4252      -- Scheme Procedure: stat:perms st
4253          An integer representing the access permission bits.
4254
4255 -- Scheme Procedure: lstat path
4256 -- C Function: scm_lstat (path)
4257     Similar to ‘stat’, but does not follow symbolic links, i.e., it
4258     will return information about a symbolic link itself, not the file
4259     it points to.  PATH must be a string.
4260
4261 -- Scheme Procedure: readlink path
4262 -- C Function: scm_readlink (path)
4263     Return the value of the symbolic link named by PATH (a string),
4264     i.e., the file that the link points to.
4265
4266 -- Scheme Procedure: chown object owner group
4267 -- C Function: scm_chown (object, owner, group)
4268     Change the ownership and group of the file referred to by OBJECT to
4269     the integer values OWNER and GROUP.  OBJECT can be a string
4270     containing a file name or, if the platform supports ‘fchown’ (*note
4271     (libc)File Owner::), a port or integer file descriptor which is
4272     open on the file.  The return value is unspecified.
4273
4274     If OBJECT is a symbolic link, either the ownership of the link or
4275     the ownership of the referenced file will be changed depending on
4276     the operating system (lchown is unsupported at present).  If OWNER
4277     or GROUP is specified as ‘-1’, then that ID is not changed.
4278
4279 -- Scheme Procedure: chmod object mode
4280 -- C Function: scm_chmod (object, mode)
4281     Changes the permissions of the file referred to by OBJECT.  OBJECT
4282     can be a string containing a file name or a port or integer file
4283     descriptor which is open on a file (in which case ‘fchmod’ is used
4284     as the underlying system call).  MODE specifies the new permissions
4285     as a decimal number, e.g., ‘(chmod "foo" #o755)’.  The return value
4286     is unspecified.
4287
4288 -- Scheme Procedure: utime pathname [actime [modtime [actimens
4289          [modtimens [flags]]]]]
4290 -- C Function: scm_utime (pathname, actime, modtime, actimens,
4291          modtimens, flags)
4292     ‘utime’ sets the access and modification times for the file named
4293     by PATHNAME.  If ACTIME or MODTIME is not supplied, then the
4294     current time is used.  ACTIME and MODTIME must be integer time
4295     values as returned by the ‘current-time’ procedure.
4296
4297     The optional ACTIMENS and MODTIMENS are nanoseconds to add ACTIME
4298     and MODTIME.  Nanosecond precision is only supported on some
4299     combinations of file systems and operating systems.
4300          (utime "foo" (- (current-time) 3600))
4301     will set the access time to one hour in the past and the
4302     modification time to the current time.
4303
4304     Last, FLAGS may be either ‘0’ or the ‘AT_SYMLINK_NOFOLLOW’
4305     constant, to set the time of PATHNAME even if it is a symbolic
4306     link.
4307
4308 -- Scheme Procedure: delete-file str
4309 -- C Function: scm_delete_file (str)
4310     Deletes (or “unlinks”) the file whose path is specified by STR.
4311
4312 -- Scheme Procedure: copy-file oldfile newfile
4313 -- C Function: scm_copy_file (oldfile, newfile)
4314     Copy the file specified by OLDFILE to NEWFILE.  The return value is
4315     unspecified.
4316
4317 -- Scheme Procedure: sendfile out in count [offset]
4318 -- C Function: scm_sendfile (out, in, count, offset)
4319     Send COUNT bytes from IN to OUT, both of which must be either open
4320     file ports or file descriptors.  When OFFSET is omitted, start
4321     reading from IN’s current position; otherwise, start reading at
4322     OFFSET.  Return the number of bytes actually sent.
4323
4324     When IN is a port, it is often preferable to specify OFFSET,
4325     because IN’s offset as a port may be different from the offset of
4326     its underlying file descriptor.
4327
4328     On systems that support it, such as GNU/Linux, this procedure uses
4329     the ‘sendfile’ libc function, which usually corresponds to a system
4330     call.  This is faster than doing a series of ‘read’ and ‘write’
4331     system calls.  A typical application is to send a file over a
4332     socket.
4333
4334     In some cases, the ‘sendfile’ libc function may return ‘EINVAL’ or
4335     ‘ENOSYS’.  In that case, Guile’s ‘sendfile’ procedure automatically
4336     falls back to doing a series of ‘read’ and ‘write’ calls.
4337
4338     In other cases, the libc function may send fewer bytes than
4339     COUNT—for instance because OUT is a slow or limited device, such as
4340     a pipe.  When that happens, Guile’s ‘sendfile’ automatically
4341     retries until exactly COUNT bytes were sent or an error occurs.
4342
4343 -- Scheme Procedure: rename-file oldname newname
4344 -- C Function: scm_rename (oldname, newname)
4345     Renames the file specified by OLDNAME to NEWNAME.  The return value
4346     is unspecified.
4347
4348 -- Scheme Procedure: link oldpath newpath
4349 -- C Function: scm_link (oldpath, newpath)
4350     Creates a new name NEWPATH in the file system for the file named by
4351     OLDPATH.  If OLDPATH is a symbolic link, the link may or may not be
4352     followed depending on the system.
4353
4354 -- Scheme Procedure: symlink oldpath newpath
4355 -- C Function: scm_symlink (oldpath, newpath)
4356     Create a symbolic link named NEWPATH with the value (i.e., pointing
4357     to) OLDPATH.  The return value is unspecified.
4358
4359 -- Scheme Procedure: mkdir path [mode]
4360 -- C Function: scm_mkdir (path, mode)
4361     Create a new directory named by PATH.  If MODE is omitted then the
4362     permissions of the directory are set to ‘#o777’ masked with the
4363     current umask (*note ‘umask’: Processes.).  Otherwise they are set
4364     to the value specified with MODE.  The return value is unspecified.
4365
4366 -- Scheme Procedure: rmdir path
4367 -- C Function: scm_rmdir (path)
4368     Remove the existing directory named by PATH.  The directory must be
4369     empty for this to succeed.  The return value is unspecified.
4370
4371 -- Scheme Procedure: opendir dirname
4372 -- C Function: scm_opendir (dirname)
4373     Open the directory specified by DIRNAME and return a directory
4374     stream.
4375
4376     Before using this and the procedures below, make sure to see the
4377     higher-level procedures for directory traversal that are available
4378     (*note File Tree Walk::).
4379
4380 -- Scheme Procedure: directory-stream? object
4381 -- C Function: scm_directory_stream_p (object)
4382     Return a boolean indicating whether OBJECT is a directory stream as
4383     returned by ‘opendir’.
4384
4385 -- Scheme Procedure: readdir stream
4386 -- C Function: scm_readdir (stream)
4387     Return (as a string) the next directory entry from the directory
4388     stream STREAM.  If there is no remaining entry to be read then the
4389     end of file object is returned.
4390
4391 -- Scheme Procedure: rewinddir stream
4392 -- C Function: scm_rewinddir (stream)
4393     Reset the directory port STREAM so that the next call to ‘readdir’
4394     will return the first directory entry.
4395
4396 -- Scheme Procedure: closedir stream
4397 -- C Function: scm_closedir (stream)
4398     Close the directory stream STREAM.  The return value is
4399     unspecified.
4400
4401   Here is an example showing how to display all the entries in a
4402directory:
4403
4404     (define dir (opendir "/usr/lib"))
4405     (do ((entry (readdir dir) (readdir dir)))
4406         ((eof-object? entry))
4407       (display entry)(newline))
4408     (closedir dir)
4409
4410 -- Scheme Procedure: sync
4411 -- C Function: scm_sync ()
4412     Flush the operating system disk buffers.  The return value is
4413     unspecified.
4414
4415 -- Scheme Procedure: mknod path type perms dev
4416 -- C Function: scm_mknod (path, type, perms, dev)
4417     Creates a new special file, such as a file corresponding to a
4418     device.  PATH specifies the name of the file.  TYPE should be one
4419     of the following symbols: ‘regular’, ‘directory’, ‘symlink’,
4420     ‘block-special’, ‘char-special’, ‘fifo’, or ‘socket’.  PERMS (an
4421     integer) specifies the file permissions.  DEV (an integer)
4422     specifies which device the special file refers to.  Its exact
4423     interpretation depends on the kind of special file being created.
4424
4425     E.g.,
4426          (mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))
4427
4428     The return value is unspecified.
4429
4430 -- Scheme Procedure: tmpnam
4431 -- C Function: scm_tmpnam ()
4432     Return an auto-generated name of a temporary file, a file which
4433     doesn’t already exist.  The name includes a path, it’s usually in
4434     ‘/tmp’ but that’s system dependent.
4435
4436     Care must be taken when using ‘tmpnam’.  In between choosing the
4437     name and creating the file another program might use that name, or
4438     an attacker might even make it a symlink pointing at something
4439     important and causing you to overwrite that.
4440
4441     The safe way is to create the file using ‘open’ with ‘O_EXCL’ to
4442     avoid any overwriting.  A loop can try again with another name if
4443     the file exists (error ‘EEXIST’).  ‘mkstemp’ below does that.
4444
4445 -- Scheme Procedure: mkstemp tmpl [mode]
4446     Create a new unique file in the file system and return a new
4447     buffered port open for reading and writing to the file.
4448
4449     TMPL is a string specifying where the file should be created: it
4450     must end with ‘XXXXXX’.  The name of the newly created file will be
4451     the same as TMPL, but with those ‘X’s changed, and can be
4452     determined by calling ‘port-filename’ on the returned port.
4453
4454     Note that the newly created file is not deleted automatically by
4455     Guile; probably the caller should arrange to call ‘delete-file’
4456     when the file is no longer needed.
4457
4458     POSIX doesn’t specify the permissions mode of the file.  On GNU and
4459     most systems it’s ‘#o600’; an application can use ‘chmod’ to relax
4460     that if desired.  For example ‘#o666’ less ‘umask’, which is usual
4461     for ordinary file creation,
4462
4463          (let ((port (mkstemp "/tmp/myfile-XXXXXX")))
4464            (chmod port (logand #o666 (lognot (umask))))
4465            ...)
4466
4467     The optional MODE argument specifies a mode with which to open the
4468     new file, as a string in the same format that ‘open-file’ takes.
4469     It defaults to ‘"w+"’.
4470
4471 -- Scheme Procedure: tmpfile
4472 -- C Function: scm_tmpfile ()
4473     Return an input/output port to a unique temporary file named using
4474     the path prefix ‘P_tmpdir’ defined in ‘stdio.h’.  The file is
4475     automatically deleted when the port is closed or the program
4476     terminates.
4477
4478 -- Scheme Procedure: mkdtemp tmpl
4479 -- C Function: scm_mkdtemp (tmpl)
4480     Create a new directory named in accordance with the template string
4481     TMPL.
4482
4483     TMPL is a string specifying the directory’s name.  The last six
4484     characters of TMPL must be ‘XXXXXX’.  Upon successful execution,
4485     the name of the new directory is returned which has the same form
4486     as TMPL but with the ‘XXXXXX’ characters modified to ensure the
4487     directory name is unique.
4488
4489     The permissions of the directory created are OS dependent, but, are
4490     usually ‘#o700’.
4491
4492     An error may be thrown if the template has the wrong format or if
4493     the directory cannot be created.
4494
4495 -- Scheme Procedure: dirname filename
4496 -- C Function: scm_dirname (filename)
4497     Return the directory name component of the file name FILENAME.  If
4498     FILENAME does not contain a directory component, ‘.’ is returned.
4499
4500 -- Scheme Procedure: basename filename [suffix]
4501 -- C Function: scm_basename (filename, suffix)
4502     Return the base name of the file name FILENAME.  The base name is
4503     the file name without any directory components.  If SUFFIX is
4504     provided, and is equal to the end of BASENAME, it is removed also.
4505
4506          (basename "/tmp/test.xml" ".xml")
4507          ⇒ "test"
4508
4509 -- Scheme Procedure: canonicalize-path path
4510 -- C Function: scm_canonicalize_path (path)
4511     Return the canonical (absolute) path of PATH.  A canonical path has
4512     no ‘.’ or ‘..’ components, nor any repeated path separators (‘/’)
4513     nor symlinks.
4514
4515     Raises an error if any component of PATH does not exist.
4516
4517          (canonicalize-path "test.xml")
4518          ⇒ "/tmp/test.xml"
4519
4520 -- Scheme Procedure: file-exists? filename
4521     Return ‘#t’ if the file named FILENAME exists, ‘#f’ if not.
4522
4523   Many operating systems, such as GNU, use ‘/’ (forward slash) to
4524separate the components of a file name; any file name starting with ‘/’
4525is considered an “absolute file name”.  These conventions are specified
4526by the POSIX Base Definitions, which refer to conforming file names as
4527“pathnames”.  Some operating systems use a different convention; in
4528particular, Windows uses ‘\’ (backslash) as the file name separator, and
4529also has the notion of “volume names” like ‘C:\’ for absolute file
4530names.  The following procedures and variables provide support for
4531portable file name manipulations.
4532
4533 -- Scheme Procedure: system-file-name-convention
4534     Return either ‘posix’ or ‘windows’, depending on what kind of
4535     system this Guile is running on.
4536
4537 -- Scheme Procedure: file-name-separator? c
4538     Return true if character C is a file name separator on the host
4539     platform.
4540
4541 -- Scheme Procedure: absolute-file-name? file-name
4542     Return true if FILE-NAME denotes an absolute file name on the host
4543     platform.
4544
4545 -- Scheme Variable: file-name-separator-string
4546     The preferred file name separator.
4547
4548     Note that on MinGW builds for Windows, both ‘/’ and ‘\’ are valid
4549     separators.  Thus, programs should not assume that
4550     ‘file-name-separator-string’ is the _only_ file name
4551     separator—e.g., when extracting the components of a file name.
4552
4553
4554File: guile.info,  Node: User Information,  Next: Time,  Prev: File System,  Up: POSIX
4555
45567.2.4 User Information
4557----------------------
4558
4559The facilities in this section provide an interface to the user and
4560group database.  They should be used with care since they are not
4561reentrant.
4562
4563   The following functions accept an object representing user
4564information and return a selected component:
4565
4566 -- Scheme Procedure: passwd:name pw
4567     The name of the userid.
4568 -- Scheme Procedure: passwd:passwd pw
4569     The encrypted passwd.
4570 -- Scheme Procedure: passwd:uid pw
4571     The user id number.
4572 -- Scheme Procedure: passwd:gid pw
4573     The group id number.
4574 -- Scheme Procedure: passwd:gecos pw
4575     The full name.
4576 -- Scheme Procedure: passwd:dir pw
4577     The home directory.
4578 -- Scheme Procedure: passwd:shell pw
4579     The login shell.
4580
4581 -- Scheme Procedure: getpwuid uid
4582     Look up an integer userid in the user database.
4583
4584 -- Scheme Procedure: getpwnam name
4585     Look up a user name string in the user database.
4586
4587 -- Scheme Procedure: setpwent
4588     Initializes a stream used by ‘getpwent’ to read from the user
4589     database.  The next use of ‘getpwent’ will return the first entry.
4590     The return value is unspecified.
4591
4592 -- Scheme Procedure: getpwent
4593     Read the next entry in the user database stream.  The return is a
4594     passwd user object as above, or ‘#f’ when no more entries.
4595
4596 -- Scheme Procedure: endpwent
4597     Closes the stream used by ‘getpwent’.  The return value is
4598     unspecified.
4599
4600 -- Scheme Procedure: setpw [arg]
4601 -- C Function: scm_setpwent (arg)
4602     If called with a true argument, initialize or reset the password
4603     data stream.  Otherwise, close the stream.  The ‘setpwent’ and
4604     ‘endpwent’ procedures are implemented on top of this.
4605
4606 -- Scheme Procedure: getpw [user]
4607 -- C Function: scm_getpwuid (user)
4608     Look up an entry in the user database.  USER can be an integer, a
4609     string, or omitted, giving the behaviour of getpwuid, getpwnam or
4610     getpwent respectively.
4611
4612   The following functions accept an object representing group
4613information and return a selected component:
4614
4615 -- Scheme Procedure: group:name gr
4616     The group name.
4617 -- Scheme Procedure: group:passwd gr
4618     The encrypted group password.
4619 -- Scheme Procedure: group:gid gr
4620     The group id number.
4621 -- Scheme Procedure: group:mem gr
4622     A list of userids which have this group as a supplementary group.
4623
4624 -- Scheme Procedure: getgrgid gid
4625     Look up an integer group id in the group database.
4626
4627 -- Scheme Procedure: getgrnam name
4628     Look up a group name in the group database.
4629
4630 -- Scheme Procedure: setgrent
4631     Initializes a stream used by ‘getgrent’ to read from the group
4632     database.  The next use of ‘getgrent’ will return the first entry.
4633     The return value is unspecified.
4634
4635 -- Scheme Procedure: getgrent
4636     Return the next entry in the group database, using the stream set
4637     by ‘setgrent’.
4638
4639 -- Scheme Procedure: endgrent
4640     Closes the stream used by ‘getgrent’.  The return value is
4641     unspecified.
4642
4643 -- Scheme Procedure: setgr [arg]
4644 -- C Function: scm_setgrent (arg)
4645     If called with a true argument, initialize or reset the group data
4646     stream.  Otherwise, close the stream.  The ‘setgrent’ and
4647     ‘endgrent’ procedures are implemented on top of this.
4648
4649 -- Scheme Procedure: getgr [group]
4650 -- C Function: scm_getgrgid (group)
4651     Look up an entry in the group database.  GROUP can be an integer, a
4652     string, or omitted, giving the behaviour of getgrgid, getgrnam or
4653     getgrent respectively.
4654
4655   In addition to the accessor procedures for the user database, the
4656following shortcut procedure is also available.
4657
4658 -- Scheme Procedure: getlogin
4659 -- C Function: scm_getlogin ()
4660     Return a string containing the name of the user logged in on the
4661     controlling terminal of the process, or ‘#f’ if this information
4662     cannot be obtained.
4663
4664
4665File: guile.info,  Node: Time,  Next: Runtime Environment,  Prev: User Information,  Up: POSIX
4666
46677.2.5 Time
4668----------
4669
4670 -- Scheme Procedure: current-time
4671 -- C Function: scm_current_time ()
4672     Return the number of seconds since 1970-01-01 00:00:00 UTC,
4673     excluding leap seconds.
4674
4675 -- Scheme Procedure: gettimeofday
4676 -- C Function: scm_gettimeofday ()
4677     Return a pair containing the number of seconds and microseconds
4678     since 1970-01-01 00:00:00 UTC, excluding leap seconds.  Note:
4679     whether true microsecond resolution is available depends on the
4680     operating system.
4681
4682   The following procedures either accept an object representing a
4683broken down time and return a selected component, or accept an object
4684representing a broken down time and a value and set the component to the
4685value.  The numbers in parentheses give the usual range.
4686
4687 -- Scheme Procedure: tm:sec tm
4688 -- Scheme Procedure: set-tm:sec tm val
4689     Seconds (0-59).
4690 -- Scheme Procedure: tm:min tm
4691 -- Scheme Procedure: set-tm:min tm val
4692     Minutes (0-59).
4693 -- Scheme Procedure: tm:hour tm
4694 -- Scheme Procedure: set-tm:hour tm val
4695     Hours (0-23).
4696 -- Scheme Procedure: tm:mday tm
4697 -- Scheme Procedure: set-tm:mday tm val
4698     Day of the month (1-31).
4699 -- Scheme Procedure: tm:mon tm
4700 -- Scheme Procedure: set-tm:mon tm val
4701     Month (0-11).
4702 -- Scheme Procedure: tm:year tm
4703 -- Scheme Procedure: set-tm:year tm val
4704     Year (70-), the year minus 1900.
4705 -- Scheme Procedure: tm:wday tm
4706 -- Scheme Procedure: set-tm:wday tm val
4707     Day of the week (0-6) with Sunday represented as 0.
4708 -- Scheme Procedure: tm:yday tm
4709 -- Scheme Procedure: set-tm:yday tm val
4710     Day of the year (0-364, 365 in leap years).
4711 -- Scheme Procedure: tm:isdst tm
4712 -- Scheme Procedure: set-tm:isdst tm val
4713     Daylight saving indicator (0 for “no”, greater than 0 for “yes”,
4714     less than 0 for “unknown”).
4715 -- Scheme Procedure: tm:gmtoff tm
4716 -- Scheme Procedure: set-tm:gmtoff tm val
4717     Time zone offset in seconds west of UTC (-46800 to 43200).  For
4718     example on East coast USA (zone ‘EST+5’) this would be 18000 (ie.
4719     5*60*60) in winter, or 14400 (ie. 4*60*60) during daylight savings.
4720
4721     Note ‘tm:gmtoff’ is not the same as ‘tm_gmtoff’ in the C ‘tm’
4722     structure.  ‘tm_gmtoff’ is seconds east and hence the negative of
4723     the value here.
4724 -- Scheme Procedure: tm:zone tm
4725 -- Scheme Procedure: set-tm:zone tm val
4726     Time zone label (a string), not necessarily unique.
4727
4728 -- Scheme Procedure: localtime time [zone]
4729 -- C Function: scm_localtime (time, zone)
4730     Return an object representing the broken down components of TIME,
4731     an integer like the one returned by ‘current-time’.  The time zone
4732     for the calculation is optionally specified by ZONE (a string),
4733     otherwise the ‘TZ’ environment variable or the system default is
4734     used.
4735
4736 -- Scheme Procedure: gmtime time
4737 -- C Function: scm_gmtime (time)
4738     Return an object representing the broken down components of TIME,
4739     an integer like the one returned by ‘current-time’.  The values are
4740     calculated for UTC.
4741
4742 -- Scheme Procedure: mktime sbd-time [zone]
4743 -- C Function: scm_mktime (sbd_time, zone)
4744     For a broken down time object SBD-TIME, return a pair the ‘car’ of
4745     which is an integer time like ‘current-time’, and the ‘cdr’ of
4746     which is a new broken down time with normalized fields.
4747
4748     ZONE is a timezone string, or the default is the ‘TZ’ environment
4749     variable or the system default (*note Specifying the Time Zone with
4750     ‘TZ’: (libc)TZ Variable.).  SBD-TIME is taken to be in that ZONE.
4751
4752     The following fields of SBD-TIME are used: ‘tm:year’, ‘tm:mon’,
4753     ‘tm:mday’, ‘tm:hour’, ‘tm:min’, ‘tm:sec’, ‘tm:isdst’.  The values
4754     can be outside their usual ranges.  For example ‘tm:hour’ normally
4755     goes up to 23, but a value say 33 would mean 9 the following day.
4756
4757     ‘tm:isdst’ in SBD-TIME says whether the time given is with daylight
4758     savings or not.  This is ignored if ZONE doesn’t have any daylight
4759     savings adjustment amount.
4760
4761     The broken down time in the return normalizes the values of
4762     SBD-TIME by bringing them into their usual ranges, and using the
4763     actual daylight savings rule for that time in ZONE (which may
4764     differ from what SBD-TIME had).  The easiest way to think of this
4765     is that SBD-TIME plus ZONE converts to the integer UTC time, then a
4766     ‘localtime’ is applied to get the normal presentation of that time,
4767     in ZONE.
4768
4769 -- Scheme Procedure: tzset
4770 -- C Function: scm_tzset ()
4771     Initialize the timezone from the ‘TZ’ environment variable or the
4772     system default.  It’s not usually necessary to call this procedure
4773     since it’s done automatically by other procedures that depend on
4774     the timezone.
4775
4776 -- Scheme Procedure: strftime format tm
4777 -- C Function: scm_strftime (format, tm)
4778     Return a string which is broken-down time structure TM formatted
4779     according to the given FORMAT string.
4780
4781     FORMAT contains field specifications introduced by a ‘%’ character.
4782     See *note (libc)Formatting Calendar Time::, or ‘man 3 strftime’,
4783     for the available formatting.
4784
4785          (strftime "%c" (localtime (current-time)))
4786          ⇒ "Mon Mar 11 20:17:43 2002"
4787
4788     If ‘setlocale’ has been called (*note Locales::), month and day
4789     names are from the current locale and in the locale character set.
4790
4791 -- Scheme Procedure: strptime format string
4792 -- C Function: scm_strptime (format, string)
4793     Performs the reverse action to ‘strftime’, parsing STRING according
4794     to the specification supplied in FORMAT.  The interpretation of
4795     month and day names is dependent on the current locale.  The value
4796     returned is a pair.  The CAR has an object with time components in
4797     the form returned by ‘localtime’ or ‘gmtime’, but the time zone
4798     components are not usefully set.  The CDR reports the number of
4799     characters from STRING which were used for the conversion.
4800
4801 -- Variable: internal-time-units-per-second
4802     The value of this variable is the number of time units per second
4803     reported by the following procedures.
4804
4805 -- Scheme Procedure: times
4806 -- C Function: scm_times ()
4807     Return an object with information about real and processor time.
4808     The following procedures accept such an object as an argument and
4809     return a selected component:
4810
4811      -- Scheme Procedure: tms:clock tms
4812          The current real time, expressed as time units relative to an
4813          arbitrary base.
4814      -- Scheme Procedure: tms:utime tms
4815          The CPU time units used by the calling process.
4816      -- Scheme Procedure: tms:stime tms
4817          The CPU time units used by the system on behalf of the calling
4818          process.
4819      -- Scheme Procedure: tms:cutime tms
4820          The CPU time units used by terminated child processes of the
4821          calling process, whose status has been collected (e.g., using
4822          ‘waitpid’).
4823      -- Scheme Procedure: tms:cstime tms
4824          Similarly, the CPU times units used by the system on behalf of
4825          terminated child processes.
4826
4827 -- Scheme Procedure: get-internal-real-time
4828 -- C Function: scm_get_internal_real_time ()
4829     Return the number of time units since the interpreter was started.
4830
4831 -- Scheme Procedure: get-internal-run-time
4832 -- C Function: scm_get_internal_run_time ()
4833     Return the number of time units of processor time used by the
4834     interpreter.  Both _system_ and _user_ time are included but
4835     subprocesses are not.
4836
4837
4838File: guile.info,  Node: Runtime Environment,  Next: Processes,  Prev: Time,  Up: POSIX
4839
48407.2.6 Runtime Environment
4841-------------------------
4842
4843 -- Scheme Procedure: program-arguments
4844 -- Scheme Procedure: command-line
4845 -- Scheme Procedure: set-program-arguments
4846 -- C Function: scm_program_arguments ()
4847 -- C Function: scm_set_program_arguments_scm (lst)
4848     Get the command line arguments passed to Guile, or set new
4849     arguments.
4850
4851     The arguments are a list of strings, the first of which is the
4852     invoked program name.  This is just "guile" (or the executable
4853     path) when run interactively, or it’s the script name when running
4854     a script with ‘-s’ (*note Invoking Guile::).
4855
4856          guile -L /my/extra/dir -s foo.scm abc def
4857
4858          (program-arguments) ⇒ ("foo.scm" "abc" "def")
4859
4860     ‘set-program-arguments’ allows a library module or similar to
4861     modify the arguments, for example to strip options it recognises,
4862     leaving the rest for the mainline.
4863
4864     The argument list is held in a fluid, which means it’s separate for
4865     each thread.  Neither the list nor the strings within it are copied
4866     at any point and normally should not be mutated.
4867
4868     The two names ‘program-arguments’ and ‘command-line’ are an
4869     historical accident, they both do exactly the same thing.  The name
4870     ‘scm_set_program_arguments_scm’ has an extra ‘_scm’ on the end to
4871     avoid clashing with the C function below.
4872
4873 -- C Function: void scm_set_program_arguments (int argc, char **argv,
4874          char *first)
4875     Set the list of command line arguments for ‘program-arguments’ and
4876     ‘command-line’ above.
4877
4878     ARGV is an array of null-terminated strings, as in a C ‘main’
4879     function.  ARGC is the number of strings in ARGV, or if it’s
4880     negative then a ‘NULL’ in ARGV marks its end.
4881
4882     FIRST is an extra string put at the start of the arguments, or
4883     ‘NULL’ for no such extra.  This is a convenient way to pass the
4884     program name after advancing ARGV to strip option arguments.  Eg.
4885
4886          {
4887            char *progname = argv[0];
4888            for (argv++; argv[0] != NULL && argv[0][0] == '-'; argv++)
4889              {
4890                /* munch option ... */
4891              }
4892            /* remaining args for scheme level use */
4893            scm_set_program_arguments (-1, argv, progname);
4894          }
4895
4896     This sort of thing is often done at startup under ‘scm_boot_guile’
4897     with options handled at the C level removed.  The given strings are
4898     all copied, so the C data is not accessed again once
4899     ‘scm_set_program_arguments’ returns.
4900
4901 -- Scheme Procedure: getenv name
4902 -- C Function: scm_getenv (name)
4903     Looks up the string NAME in the current environment.  The return
4904     value is ‘#f’ unless a string of the form ‘NAME=VALUE’ is found, in
4905     which case the string ‘VALUE’ is returned.
4906
4907 -- Scheme Procedure: setenv name value
4908     Modifies the environment of the current process, which is also the
4909     default environment inherited by child processes.
4910
4911     If VALUE is ‘#f’, then NAME is removed from the environment.
4912     Otherwise, the string NAME=VALUE is added to the environment,
4913     replacing any existing string with name matching NAME.
4914
4915     The return value is unspecified.
4916
4917 -- Scheme Procedure: unsetenv name
4918     Remove variable NAME from the environment.  The name can not
4919     contain a ‘=’ character.
4920
4921 -- Scheme Procedure: environ [env]
4922 -- C Function: scm_environ (env)
4923     If ENV is omitted, return the current environment (in the Unix
4924     sense) as a list of strings.  Otherwise set the current
4925     environment, which is also the default environment for child
4926     processes, to the supplied list of strings.  Each member of ENV
4927     should be of the form NAME=VALUE and values of NAME should not be
4928     duplicated.  If ENV is supplied then the return value is
4929     unspecified.
4930
4931 -- Scheme Procedure: putenv str
4932 -- C Function: scm_putenv (str)
4933     Modifies the environment of the current process, which is also the
4934     default environment inherited by child processes.
4935
4936     If STR is of the form ‘NAME=VALUE’ then it will be written directly
4937     into the environment, replacing any existing environment string
4938     with name matching ‘NAME’.  If STR does not contain an equal sign,
4939     then any existing string with name matching STR will be removed.
4940
4941     The return value is unspecified.
4942
4943
4944File: guile.info,  Node: Processes,  Next: Signals,  Prev: Runtime Environment,  Up: POSIX
4945
49467.2.7 Processes
4947---------------
4948
4949 -- Scheme Procedure: chdir str
4950 -- C Function: scm_chdir (str)
4951     Change the current working directory to STR.  The return value is
4952     unspecified.
4953
4954 -- Scheme Procedure: getcwd
4955 -- C Function: scm_getcwd ()
4956     Return the name of the current working directory.
4957
4958 -- Scheme Procedure: umask [mode]
4959 -- C Function: scm_umask (mode)
4960     If MODE is omitted, returns a decimal number representing the
4961     current file creation mask.  Otherwise the file creation mask is
4962     set to MODE and the previous value is returned.  *Note Assigning
4963     File Permissions: (libc)Setting Permissions, for more on how to use
4964     umasks.
4965
4966     E.g., ‘(umask #o022)’ sets the mask to octal 22/decimal 18.
4967
4968 -- Scheme Procedure: chroot path
4969 -- C Function: scm_chroot (path)
4970     Change the root directory to that specified in PATH.  This
4971     directory will be used for path names beginning with ‘/’.  The root
4972     directory is inherited by all children of the current process.
4973     Only the superuser may change the root directory.
4974
4975 -- Scheme Procedure: getpid
4976 -- C Function: scm_getpid ()
4977     Return an integer representing the current process ID.
4978
4979 -- Scheme Procedure: getgroups
4980 -- C Function: scm_getgroups ()
4981     Return a vector of integers representing the current supplementary
4982     group IDs.
4983
4984 -- Scheme Procedure: getppid
4985 -- C Function: scm_getppid ()
4986     Return an integer representing the process ID of the parent
4987     process.
4988
4989 -- Scheme Procedure: getuid
4990 -- C Function: scm_getuid ()
4991     Return an integer representing the current real user ID.
4992
4993 -- Scheme Procedure: getgid
4994 -- C Function: scm_getgid ()
4995     Return an integer representing the current real group ID.
4996
4997 -- Scheme Procedure: geteuid
4998 -- C Function: scm_geteuid ()
4999     Return an integer representing the current effective user ID. If
5000     the system does not support effective IDs, then the real ID is
5001     returned.  ‘(provided? 'EIDs)’ reports whether the system supports
5002     effective IDs.
5003
5004 -- Scheme Procedure: getegid
5005 -- C Function: scm_getegid ()
5006     Return an integer representing the current effective group ID. If
5007     the system does not support effective IDs, then the real ID is
5008     returned.  ‘(provided? 'EIDs)’ reports whether the system supports
5009     effective IDs.
5010
5011 -- Scheme Procedure: setgroups vec
5012 -- C Function: scm_setgroups (vec)
5013     Set the current set of supplementary group IDs to the integers in
5014     the given vector VEC.  The return value is unspecified.
5015
5016     Generally only the superuser can set the process group IDs (*note
5017     Setting the Group IDs: (libc)Setting Groups.).
5018
5019 -- Scheme Procedure: setuid id
5020 -- C Function: scm_setuid (id)
5021     Sets both the real and effective user IDs to the integer ID,
5022     provided the process has appropriate privileges.  The return value
5023     is unspecified.
5024
5025 -- Scheme Procedure: setgid id
5026 -- C Function: scm_setgid (id)
5027     Sets both the real and effective group IDs to the integer ID,
5028     provided the process has appropriate privileges.  The return value
5029     is unspecified.
5030
5031 -- Scheme Procedure: seteuid id
5032 -- C Function: scm_seteuid (id)
5033     Sets the effective user ID to the integer ID, provided the process
5034     has appropriate privileges.  If effective IDs are not supported,
5035     the real ID is set instead—‘(provided? 'EIDs)’ reports whether the
5036     system supports effective IDs.  The return value is unspecified.
5037
5038 -- Scheme Procedure: setegid id
5039 -- C Function: scm_setegid (id)
5040     Sets the effective group ID to the integer ID, provided the process
5041     has appropriate privileges.  If effective IDs are not supported,
5042     the real ID is set instead—‘(provided? 'EIDs)’ reports whether the
5043     system supports effective IDs.  The return value is unspecified.
5044
5045 -- Scheme Procedure: getpgrp
5046 -- C Function: scm_getpgrp ()
5047     Return an integer representing the current process group ID. This
5048     is the POSIX definition, not BSD.
5049
5050 -- Scheme Procedure: setpgid pid pgid
5051 -- C Function: scm_setpgid (pid, pgid)
5052     Move the process PID into the process group PGID.  PID or PGID must
5053     be integers: they can be zero to indicate the ID of the current
5054     process.  Fails on systems that do not support job control.  The
5055     return value is unspecified.
5056
5057 -- Scheme Procedure: setsid
5058 -- C Function: scm_setsid ()
5059     Creates a new session.  The current process becomes the session
5060     leader and is put in a new process group.  The process will be
5061     detached from its controlling terminal if it has one.  The return
5062     value is an integer representing the new process group ID.
5063
5064 -- Scheme Procedure: getsid pid
5065 -- C Function: scm_getsid (pid)
5066     Returns the session ID of process PID.  (The session ID of a
5067     process is the process group ID of its session leader.)
5068
5069 -- Scheme Procedure: waitpid pid [options]
5070 -- C Function: scm_waitpid (pid, options)
5071     This procedure collects status information from a child process
5072     which has terminated or (optionally) stopped.  Normally it will
5073     suspend the calling process until this can be done.  If more than
5074     one child process is eligible then one will be chosen by the
5075     operating system.
5076
5077     The value of PID determines the behaviour:
5078
5079     PID greater than 0
5080          Request status information from the specified child process.
5081     PID equal to -1 or ‘WAIT_ANY’
5082          Request status information for any child process.
5083     PID equal to 0 or ‘WAIT_MYPGRP’
5084          Request status information for any child process in the
5085          current process group.
5086     PID less than -1
5087          Request status information for any child process whose process
5088          group ID is −PID.
5089
5090     The OPTIONS argument, if supplied, should be the bitwise OR of the
5091     values of zero or more of the following variables:
5092
5093      -- Variable: WNOHANG
5094          Return immediately even if there are no child processes to be
5095          collected.
5096
5097      -- Variable: WUNTRACED
5098          Report status information for stopped processes as well as
5099          terminated processes.
5100
5101     The return value is a pair containing:
5102
5103       1. The process ID of the child process, or 0 if ‘WNOHANG’ was
5104          specified and no process was collected.
5105       2. The integer status value (*note (libc)Process Completion
5106          Status::).
5107
5108   The following three functions can be used to decode the integer
5109status value returned by ‘waitpid’.
5110
5111 -- Scheme Procedure: status:exit-val status
5112 -- C Function: scm_status_exit_val (status)
5113     Return the exit status value, as would be set if a process ended
5114     normally through a call to ‘exit’ or ‘_exit’, if any, otherwise
5115     ‘#f’.
5116
5117 -- Scheme Procedure: status:term-sig status
5118 -- C Function: scm_status_term_sig (status)
5119     Return the signal number which terminated the process, if any,
5120     otherwise ‘#f’.
5121
5122 -- Scheme Procedure: status:stop-sig status
5123 -- C Function: scm_status_stop_sig (status)
5124     Return the signal number which stopped the process, if any,
5125     otherwise ‘#f’.
5126
5127 -- Scheme Procedure: system [cmd]
5128 -- C Function: scm_system (cmd)
5129     Execute CMD using the operating system’s “command processor”.
5130     Under Unix this is usually the default shell ‘sh’.  The value
5131     returned is CMD’s exit status as returned by ‘waitpid’, which can
5132     be interpreted using the functions above.
5133
5134     If ‘system’ is called without arguments, return a boolean
5135     indicating whether the command processor is available.
5136
5137 -- Scheme Procedure: system* arg1 arg2 ...
5138 -- C Function: scm_system_star (args)
5139     Execute the command indicated by ARG1 ARG2 ....  The first element
5140     must be a string indicating the command to be executed, and the
5141     remaining items must be strings representing each of the arguments
5142     to that command.
5143
5144     This function returns the exit status of the command as provided by
5145     ‘waitpid’.  This value can be handled with ‘status:exit-val’ and
5146     the related functions.
5147
5148     ‘system*’ is similar to ‘system’, but accepts only one string
5149     per-argument, and performs no shell interpretation.  The command is
5150     executed using fork and execlp.  Accordingly this function may be
5151     safer than ‘system’ in situations where shell interpretation is not
5152     required.
5153
5154     Example: (system* "echo" "foo" "bar")
5155
5156 -- Scheme Procedure: quit [status]
5157 -- Scheme Procedure: exit [status]
5158     Terminate the current process with proper unwinding of the Scheme
5159     stack.  The exit status zero if STATUS is not supplied.  If STATUS
5160     is supplied, and it is an integer, that integer is used as the exit
5161     status.  If STATUS is ‘#t’ or ‘#f’, the exit status is EXIT_SUCCESS
5162     or EXIT_FAILURE, respectively.
5163
5164     The procedure ‘exit’ is an alias of ‘quit’.  They have the same
5165     functionality.
5166
5167 -- Scheme Variable: EXIT_SUCCESS
5168 -- Scheme Variable: EXIT_FAILURE
5169     These constants represent the standard exit codes for success
5170     (zero) or failure (one.)
5171
5172 -- Scheme Procedure: primitive-exit [status]
5173 -- Scheme Procedure: primitive-_exit [status]
5174 -- C Function: scm_primitive_exit (status)
5175 -- C Function: scm_primitive__exit (status)
5176     Terminate the current process without unwinding the Scheme stack.
5177     The exit status is STATUS if supplied, otherwise zero.
5178
5179     ‘primitive-exit’ uses the C ‘exit’ function and hence runs usual C
5180     level cleanups (flush output streams, call ‘atexit’ functions, etc,
5181     see *note (libc)Normal Termination::)).
5182
5183     ‘primitive-_exit’ is the ‘_exit’ system call (*note
5184     (libc)Termination Internals::).  This terminates the program
5185     immediately, with neither Scheme-level nor C-level cleanups.
5186
5187     The typical use for ‘primitive-_exit’ is from a child process
5188     created with ‘primitive-fork’.  For example in a Gdk program the
5189     child process inherits the X server connection and a C-level
5190     ‘atexit’ cleanup which will close that connection.  But closing in
5191     the child would upset the protocol in the parent, so
5192     ‘primitive-_exit’ should be used to exit without that.
5193
5194 -- Scheme Procedure: execl filename arg ...
5195 -- C Function: scm_execl (filename, args)
5196     Executes the file named by FILENAME as a new process image.  The
5197     remaining arguments are supplied to the process; from a C program
5198     they are accessible as the ‘argv’ argument to ‘main’.
5199     Conventionally the first ARG is the same as FILENAME.  All
5200     arguments must be strings.
5201
5202     If ARG is missing, FILENAME is executed with a null argument list,
5203     which may have system-dependent side-effects.
5204
5205     This procedure is currently implemented using the ‘execv’ system
5206     call, but we call it ‘execl’ because of its Scheme calling
5207     interface.
5208
5209 -- Scheme Procedure: execlp filename arg ...
5210 -- C Function: scm_execlp (filename, args)
5211     Similar to ‘execl’, however if FILENAME does not contain a slash
5212     then the file to execute will be located by searching the
5213     directories listed in the ‘PATH’ environment variable.
5214
5215     This procedure is currently implemented using the ‘execvp’ system
5216     call, but we call it ‘execlp’ because of its Scheme calling
5217     interface.
5218
5219 -- Scheme Procedure: execle filename env arg ...
5220 -- C Function: scm_execle (filename, env, args)
5221     Similar to ‘execl’, but the environment of the new process is
5222     specified by ENV, which must be a list of strings as returned by
5223     the ‘environ’ procedure.
5224
5225     This procedure is currently implemented using the ‘execve’ system
5226     call, but we call it ‘execle’ because of its Scheme calling
5227     interface.
5228
5229 -- Scheme Procedure: primitive-fork
5230 -- C Function: scm_fork ()
5231     Creates a new “child” process by duplicating the current “parent”
5232     process.  In the child the return value is 0.  In the parent the
5233     return value is the integer process ID of the child.
5234
5235     Note that it is unsafe to fork a process that has multiple threads
5236     running, as only the thread that calls ‘primitive-fork’ will
5237     persist in the child.  Any resources that other threads held, such
5238     as locked mutexes or open file descriptors, are lost.  Indeed,
5239     POSIX specifies that only async-signal-safe procedures are safe to
5240     call after a multithreaded fork, which is a very limited set.
5241     Guile issues a warning if it detects a fork from a multi-threaded
5242     program.
5243
5244     If you are going to ‘exec’ soon after forking, the procedures in
5245     ‘(ice-9 popen)’ may be useful to you, as they fork and exec within
5246     an async-signal-safe function carefully written to ensure robust
5247     program behavior, even in the presence of threads.  *Note Pipes::,
5248     for more.
5249
5250     This procedure has been renamed from ‘fork’ to avoid a naming
5251     conflict with the scsh fork.
5252
5253 -- Scheme Procedure: nice incr
5254 -- C Function: scm_nice (incr)
5255     Increment the priority of the current process by INCR.  A higher
5256     priority value means that the process runs less often.  The return
5257     value is unspecified.
5258
5259 -- Scheme Procedure: setpriority which who prio
5260 -- C Function: scm_setpriority (which, who, prio)
5261     Set the scheduling priority of the process, process group or user,
5262     as indicated by WHICH and WHO.  WHICH is one of the variables
5263     ‘PRIO_PROCESS’, ‘PRIO_PGRP’ or ‘PRIO_USER’, and WHO is interpreted
5264     relative to WHICH (a process identifier for ‘PRIO_PROCESS’, process
5265     group identifier for ‘PRIO_PGRP’, and a user identifier for
5266     ‘PRIO_USER’.  A zero value of WHO denotes the current process,
5267     process group, or user.  PRIO is a value in the range [−20,20].
5268     The default priority is 0; lower priorities (in numerical terms)
5269     cause more favorable scheduling.  Sets the priority of all of the
5270     specified processes.  Only the super-user may lower priorities.
5271     The return value is not specified.
5272
5273 -- Scheme Procedure: getpriority which who
5274 -- C Function: scm_getpriority (which, who)
5275     Return the scheduling priority of the process, process group or
5276     user, as indicated by WHICH and WHO.  WHICH is one of the variables
5277     ‘PRIO_PROCESS’, ‘PRIO_PGRP’ or ‘PRIO_USER’, and WHO should be
5278     interpreted depending on WHICH (a process identifier for
5279     ‘PRIO_PROCESS’, process group identifier for ‘PRIO_PGRP’, and a
5280     user identifier for ‘PRIO_USER’).  A zero value of WHO denotes the
5281     current process, process group, or user.  Return the highest
5282     priority (lowest numerical value) of any of the specified
5283     processes.
5284
5285 -- Scheme Procedure: getaffinity pid
5286 -- C Function: scm_getaffinity (pid)
5287     Return a bitvector representing the CPU affinity mask for process
5288     PID.  Each CPU the process has affinity with has its corresponding
5289     bit set in the returned bitvector.  The number of bits set is a
5290     good estimate of how many CPUs Guile can use without stepping on
5291     other processes’ toes.
5292
5293     Currently this procedure is only defined on GNU variants (*note
5294     ‘sched_getaffinity’: (libc)CPU Affinity.).
5295
5296 -- Scheme Procedure: setaffinity pid mask
5297 -- C Function: scm_setaffinity (pid, mask)
5298     Install the CPU affinity mask MASK, a bitvector, for the process or
5299     thread with ID PID.  The return value is unspecified.
5300
5301     Currently this procedure is only defined on GNU variants (*note
5302     ‘sched_setaffinity’: (libc)CPU Affinity.).
5303
5304   *Note Threads::, for information on how get the number of processors
5305available on a system.
5306
5307
5308File: guile.info,  Node: Signals,  Next: Terminals and Ptys,  Prev: Processes,  Up: POSIX
5309
53107.2.8 Signals
5311-------------
5312
5313The following procedures raise, handle and wait for signals.
5314
5315   Scheme code signal handlers are run via an async (*note Asyncs::), so
5316they’re called in the handler’s thread at the next safe opportunity.
5317Generally this is after any currently executing primitive procedure
5318finishes (which could be a long time for primitives that wait for an
5319external event).
5320
5321 -- Scheme Procedure: kill pid sig
5322 -- C Function: scm_kill (pid, sig)
5323     Sends a signal to the specified process or group of processes.
5324
5325     PID specifies the processes to which the signal is sent:
5326
5327     PID greater than 0
5328          The process whose identifier is PID.
5329     PID equal to 0
5330          All processes in the current process group.
5331     PID less than -1
5332          The process group whose identifier is -PID
5333     PID equal to -1
5334          If the process is privileged, all processes except for some
5335          special system processes.  Otherwise, all processes with the
5336          current effective user ID.
5337
5338     SIG should be specified using a variable corresponding to the Unix
5339     symbolic name, e.g.,
5340
5341      -- Variable: SIGHUP
5342          Hang-up signal.
5343
5344      -- Variable: SIGINT
5345          Interrupt signal.
5346
5347     A full list of signals on the GNU system may be found in *note
5348     (libc)Standard Signals::.
5349
5350 -- Scheme Procedure: raise sig
5351 -- C Function: scm_raise (sig)
5352     Sends a specified signal SIG to the current process, where SIG is
5353     as described for the ‘kill’ procedure.
5354
5355 -- Scheme Procedure: sigaction signum [handler [flags [thread]]]
5356 -- C Function: scm_sigaction (signum, handler, flags)
5357 -- C Function: scm_sigaction_for_thread (signum, handler, flags,
5358          thread)
5359     Install or report the signal handler for a specified signal.
5360
5361     SIGNUM is the signal number, which can be specified using the value
5362     of variables such as ‘SIGINT’.
5363
5364     If HANDLER is omitted, ‘sigaction’ returns a pair: the CAR is the
5365     current signal hander, which will be either an integer with the
5366     value ‘SIG_DFL’ (default action) or ‘SIG_IGN’ (ignore), or the
5367     Scheme procedure which handles the signal, or ‘#f’ if a non-Scheme
5368     procedure handles the signal.  The CDR contains the current
5369     ‘sigaction’ flags for the handler.
5370
5371     If HANDLER is provided, it is installed as the new handler for
5372     SIGNUM.  HANDLER can be a Scheme procedure taking one argument, or
5373     the value of ‘SIG_DFL’ (default action) or ‘SIG_IGN’ (ignore), or
5374     ‘#f’ to restore whatever signal handler was installed before
5375     ‘sigaction’ was first used.  When a scheme procedure has been
5376     specified, that procedure will run in the given THREAD.  When no
5377     thread has been given, the thread that made this call to
5378     ‘sigaction’ is used.
5379
5380     FLAGS is a ‘logior’ (*note Bitwise Operations::) of the following
5381     (where provided by the system), or ‘0’ for none.
5382
5383      -- Variable: SA_NOCLDSTOP
5384          By default, ‘SIGCHLD’ is signalled when a child process stops
5385          (ie. receives ‘SIGSTOP’), and when a child process terminates.
5386          With the ‘SA_NOCLDSTOP’ flag, ‘SIGCHLD’ is only signalled for
5387          termination, not stopping.
5388
5389          ‘SA_NOCLDSTOP’ has no effect on signals other than ‘SIGCHLD’.
5390
5391      -- Variable: SA_RESTART
5392          If a signal occurs while in a system call, deliver the signal
5393          then restart the system call (as opposed to returning an
5394          ‘EINTR’ error from that call).
5395
5396     Guile handles signals asynchronously.  When it receives a signal,
5397     the synchronous signal handler just records the fact that a signal
5398     was received and sets a flag to tell the relevant Guile thread that
5399     it has a pending signal.  When the Guile thread checks the
5400     pending-interrupt flag, it will arrange to run the asynchronous
5401     part of the signal handler, which is the handler attached by
5402     ‘sigaction’.
5403
5404     This strategy has some perhaps-unexpected interactions with the
5405     ‘SA_RESTART’ flag, though: because the synchronous handler doesn’t
5406     do very much, and notably it doesn’t run the Guile handler, it’s
5407     impossible to interrupt a thread stuck in a long-running system
5408     call via a signal handler that is installed with ‘SA_RESTART’: the
5409     synchronous handler just records the pending interrupt, but then
5410     the system call resumes and Guile doesn’t have a chance to actually
5411     check the flag and run the asynchronous handler.  That’s just how
5412     it is.
5413
5414     The return value is a pair with information about the old handler
5415     as described above.
5416
5417     This interface does not provide access to the “signal blocking”
5418     facility.  Maybe this is not needed, since the thread support may
5419     provide solutions to the problem of consistent access to data
5420     structures.
5421
5422 -- Scheme Procedure: restore-signals
5423 -- C Function: scm_restore_signals ()
5424     Return all signal handlers to the values they had before any call
5425     to ‘sigaction’ was made.  The return value is unspecified.
5426
5427 -- Scheme Procedure: alarm i
5428 -- C Function: scm_alarm (i)
5429     Set a timer to raise a ‘SIGALRM’ signal after the specified number
5430     of seconds (an integer).  It’s advisable to install a signal
5431     handler for ‘SIGALRM’ beforehand, since the default action is to
5432     terminate the process.
5433
5434     The return value indicates the time remaining for the previous
5435     alarm, if any.  The new value replaces the previous alarm.  If
5436     there was no previous alarm, the return value is zero.
5437
5438 -- Scheme Procedure: pause
5439 -- C Function: scm_pause ()
5440     Pause the current process (thread?)  until a signal arrives whose
5441     action is to either terminate the current process or invoke a
5442     handler procedure.  The return value is unspecified.
5443
5444 -- Scheme Procedure: sleep secs
5445 -- Scheme Procedure: usleep usecs
5446 -- C Function: scm_sleep (secs)
5447 -- C Function: scm_usleep (usecs)
5448     Wait the given period SECS seconds or USECS microseconds (both
5449     integers).  If a signal arrives the wait stops and the return value
5450     is the time remaining, in seconds or microseconds respectively.  If
5451     the period elapses with no signal the return is zero.
5452
5453     On most systems the process scheduler is not microsecond accurate
5454     and the actual period slept by ‘usleep’ might be rounded to a
5455     system clock tick boundary, which might be 10 milliseconds for
5456     instance.
5457
5458     See ‘scm_std_sleep’ and ‘scm_std_usleep’ for equivalents at the C
5459     level (*note Blocking::).
5460
5461 -- Scheme Procedure: getitimer which_timer
5462 -- Scheme Procedure: setitimer which_timer interval_seconds
5463          interval_microseconds value_seconds value_microseconds
5464 -- C Function: scm_getitimer (which_timer)
5465 -- C Function: scm_setitimer (which_timer, interval_seconds,
5466          interval_microseconds, value_seconds, value_microseconds)
5467     Get or set the periods programmed in certain system timers.
5468
5469     These timers have two settings.  The first setting, the interval,
5470     is the value at which the timer will be reset when the current
5471     timer expires.  The second is the current value of the timer,
5472     indicating when the next expiry will be signalled.
5473
5474     WHICH_TIMER is one of the following values:
5475
5476      -- Variable: ITIMER_REAL
5477          A real-time timer, counting down elapsed real time.  At zero
5478          it raises ‘SIGALRM’.  This is like ‘alarm’ above, but with a
5479          higher resolution period.
5480
5481      -- Variable: ITIMER_VIRTUAL
5482          A virtual-time timer, counting down while the current process
5483          is actually using CPU. At zero it raises ‘SIGVTALRM’.
5484
5485      -- Variable: ITIMER_PROF
5486          A profiling timer, counting down while the process is running
5487          (like ‘ITIMER_VIRTUAL’) and also while system calls are
5488          running on the process’s behalf.  At zero it raises a
5489          ‘SIGPROF’.
5490
5491          This timer is intended for profiling where a program is
5492          spending its time (by looking where it is when the timer goes
5493          off).
5494
5495     ‘getitimer’ returns the restart timer value and its current value,
5496     as a list containing two pairs.  Each pair is a time in seconds and
5497     microseconds: ‘((INTERVAL_SECS . INTERVAL_USECS) (VALUE_SECS .
5498     VALUE_USECS))’.
5499
5500     ‘setitimer’ sets the timer values similarly, in seconds and
5501     microseconds (which must be integers).  The interval value can be
5502     zero to have the timer run down just once.  The return value is the
5503     timer’s previous setting, in the same form as ‘getitimer’ returns.
5504
5505          (setitimer ITIMER_REAL
5506                     5 500000     ;; Raise SIGALRM every 5.5 seconds
5507                     2 0)         ;; with the first SIGALRM in 2 seconds
5508
5509     Although the timers are programmed in microseconds, the actual
5510     accuracy might not be that high.
5511
5512     Note that ‘ITIMER_PROF’ and ‘ITIMER_VIRTUAL’ are not functional on
5513     all platforms and may always error when called.  ‘(provided?
5514     'ITIMER_PROF)’ and ‘(provided? 'ITIMER_VIRTUAL)’ can be used to
5515     test if the those itimers are supported on the given host.
5516     ‘ITIMER_REAL’ is supported on all platforms that support
5517     ‘setitimer’.
5518
5519
5520File: guile.info,  Node: Terminals and Ptys,  Next: Pipes,  Prev: Signals,  Up: POSIX
5521
55227.2.9 Terminals and Ptys
5523------------------------
5524
5525 -- Scheme Procedure: isatty? port
5526 -- C Function: scm_isatty_p (port)
5527     Return ‘#t’ if PORT is using a serial non–file device, otherwise
5528     ‘#f’.
5529
5530 -- Scheme Procedure: ttyname port
5531 -- C Function: scm_ttyname (port)
5532     Return a string with the name of the serial terminal device
5533     underlying PORT.
5534
5535 -- Scheme Procedure: ctermid
5536 -- C Function: scm_ctermid ()
5537     Return a string containing the file name of the controlling
5538     terminal for the current process.
5539
5540 -- Scheme Procedure: tcgetpgrp port
5541 -- C Function: scm_tcgetpgrp (port)
5542     Return the process group ID of the foreground process group
5543     associated with the terminal open on the file descriptor underlying
5544     PORT.
5545
5546     If there is no foreground process group, the return value is a
5547     number greater than 1 that does not match the process group ID of
5548     any existing process group.  This can happen if all of the
5549     processes in the job that was formerly the foreground job have
5550     terminated, and no other job has yet been moved into the
5551     foreground.
5552
5553 -- Scheme Procedure: tcsetpgrp port pgid
5554 -- C Function: scm_tcsetpgrp (port, pgid)
5555     Set the foreground process group ID for the terminal used by the
5556     file descriptor underlying PORT to the integer PGID.  The calling
5557     process must be a member of the same session as PGID and must have
5558     the same controlling terminal.  The return value is unspecified.
5559
5560
5561File: guile.info,  Node: Pipes,  Next: Networking,  Prev: Terminals and Ptys,  Up: POSIX
5562
55637.2.10 Pipes
5564------------
5565
5566The following procedures are similar to the ‘popen’ and ‘pclose’ system
5567routines.  The code is in a separate “popen” module(1):
5568
5569     (use-modules (ice-9 popen))
5570
5571 -- Scheme Procedure: open-pipe command mode
5572 -- Scheme Procedure: open-pipe* mode prog [args...]
5573     Execute a command in a subprocess, with a pipe to it or from it, or
5574     with pipes in both directions.
5575
5576     ‘open-pipe’ runs the shell COMMAND using ‘/bin/sh -c’.
5577     ‘open-pipe*’ executes PROG directly, with the optional ARGS
5578     arguments (all strings).
5579
5580     MODE should be one of the following values.  ‘OPEN_READ’ is an
5581     input pipe, ie. to read from the subprocess.  ‘OPEN_WRITE’ is an
5582     output pipe, ie. to write to it.
5583
5584      -- Variable: OPEN_READ
5585      -- Variable: OPEN_WRITE
5586      -- Variable: OPEN_BOTH
5587
5588     For an input pipe, the child’s standard output is the pipe and
5589     standard input is inherited from ‘current-input-port’.  For an
5590     output pipe, the child’s standard input is the pipe and standard
5591     output is inherited from ‘current-output-port’.  In all cases the
5592     child’s standard error is inherited from ‘current-error-port’
5593     (*note Default Ports::).
5594
5595     If those ‘current-X-ports’ are not files of some kind, and hence
5596     don’t have file descriptors for the child, then ‘/dev/null’ is used
5597     instead.
5598
5599     Care should be taken with ‘OPEN_BOTH’, a deadlock will occur if
5600     both parent and child are writing, and waiting until the write
5601     completes before doing any reading.  Each direction has ‘PIPE_BUF’
5602     bytes of buffering (*note Buffering::), which will be enough for
5603     small writes, but not for say putting a big file through a filter.
5604
5605 -- Scheme Procedure: open-input-pipe command
5606     Equivalent to ‘open-pipe’ with mode ‘OPEN_READ’.
5607
5608          (let* ((port (open-input-pipe "date --utc"))
5609                 (str  (read-line port))) ; from (ice-9 rdelim)
5610            (close-pipe port)
5611            str)
5612          ⇒ "Mon Mar 11 20:10:44 UTC 2002"
5613
5614 -- Scheme Procedure: open-output-pipe command
5615     Equivalent to ‘open-pipe’ with mode ‘OPEN_WRITE’.
5616
5617          (let ((port (open-output-pipe "lpr")))
5618            (display "Something for the line printer.\n" port)
5619            (if (not (eqv? 0 (status:exit-val (close-pipe port))))
5620                (error "Cannot print")))
5621
5622 -- Scheme Procedure: open-input-output-pipe command
5623     Equivalent to ‘open-pipe’ with mode ‘OPEN_BOTH’.
5624
5625 -- Scheme Procedure: close-pipe port
5626     Close a pipe created by ‘open-pipe’, wait for the process to
5627     terminate, and return the wait status code.  The status is as per
5628     ‘waitpid’ and can be decoded with ‘status:exit-val’ etc (*note
5629     Processes::)
5630
5631
5632   ‘waitpid WAIT_ANY’ should not be used when pipes are open, since it
5633can reap a pipe’s child process, causing an error from a subsequent
5634‘close-pipe’.
5635
5636   ‘close-port’ (*note Ports::) can close a pipe, but it doesn’t reap
5637the child process.
5638
5639   The garbage collector will close a pipe no longer in use, and reap
5640the child process with ‘waitpid’.  If the child hasn’t yet terminated
5641the garbage collector doesn’t block, but instead checks again in the
5642next GC.
5643
5644   Many systems have per-user and system-wide limits on the number of
5645processes, and a system-wide limit on the number of pipes, so pipes
5646should be closed explicitly when no longer needed, rather than letting
5647the garbage collector pick them up at some later time.
5648
5649 -- Scheme Procedure: pipeline COMMANDS
5650     Execute a pipeline of COMMANDS, where each command is a list of a
5651     program and its arguments as strings, returning an input port to
5652     the end of the pipeline, an output port to the beginning of the
5653     pipeline and a list of PIDs of the processes executing the
5654     COMMANDS.
5655
5656          (let ((commands '(("git" "ls-files")
5657                            ("tar" "-cf-" "-T-")
5658                            ("sha1sum" "-")))
5659                (success? (lambda (pid)
5660                            (zero?
5661                             (status:exit-val (cdr (waitpid pid)))))))
5662            (receive (from to pids) (pipeline commands)
5663              (let* ((sha1 (read-delimited " " from))
5664                     (index (list-index (negate success?) (reverse pids))))
5665                (close to)
5666                (close from)
5667                (if (not index)
5668                    sha1
5669                    (string-append "pipeline failed in command: "
5670                                   (string-join (list-ref commands index)))))))
5671          ⇒ "52f99d234503fca8c84ef94b1005a3a28d8b3bc1"
5672
5673   ---------- Footnotes ----------
5674
5675   (1) This module is only available on systems where the ‘popen’
5676feature is provided (*note Common Feature Symbols::).
5677
5678
5679File: guile.info,  Node: Networking,  Next: System Identification,  Prev: Pipes,  Up: POSIX
5680
56817.2.11 Networking
5682-----------------
5683
5684* Menu:
5685
5686* Network Address Conversion::
5687* Network Databases::
5688* Network Socket Address::
5689* Network Sockets and Communication::
5690* Internet Socket Examples::
5691
5692
5693File: guile.info,  Node: Network Address Conversion,  Next: Network Databases,  Up: Networking
5694
56957.2.11.1 Network Address Conversion
5696...................................
5697
5698This section describes procedures which convert internet addresses
5699between numeric and string formats.
5700
5701IPv4 Address Conversion
5702.......................
5703
5704An IPv4 Internet address is a 4-byte value, represented in Guile as an
5705integer in host byte order, so that say “0.0.0.1” is 1, or “1.0.0.0” is
570616777216.
5707
5708   Some underlying C functions use network byte order for addresses,
5709Guile converts as necessary so that at the Scheme level its host byte
5710order everywhere.
5711
5712 -- Variable: INADDR_ANY
5713     For a server, this can be used with ‘bind’ (*note Network Sockets
5714     and Communication::) to allow connections from any interface on the
5715     machine.
5716
5717 -- Variable: INADDR_BROADCAST
5718     The broadcast address on the local network.
5719
5720 -- Variable: INADDR_LOOPBACK
5721     The address of the local host using the loopback device, ie.
5722     ‘127.0.0.1’.
5723
5724 -- Scheme Procedure: inet-netof address
5725 -- C Function: scm_inet_netof (address)
5726     Return the network number part of the given IPv4 Internet address.
5727     E.g.,
5728
5729          (inet-netof 2130706433) ⇒ 127
5730
5731 -- Scheme Procedure: inet-lnaof address
5732 -- C Function: scm_lnaof (address)
5733     Return the local-address-with-network part of the given IPv4
5734     Internet address, using the obsolete class A/B/C system.  E.g.,
5735
5736          (inet-lnaof 2130706433) ⇒ 1
5737
5738 -- Scheme Procedure: inet-makeaddr net lna
5739 -- C Function: scm_inet_makeaddr (net, lna)
5740     Make an IPv4 Internet address by combining the network number NET
5741     with the local-address-within-network number LNA.  E.g.,
5742
5743          (inet-makeaddr 127 1) ⇒ 2130706433
5744
5745IPv6 Address Conversion
5746.......................
5747
5748An IPv6 Internet address is a 16-byte value, represented in Guile as an
5749integer in host byte order, so that say “::1” is 1.
5750
5751 -- Scheme Procedure: inet-ntop family address
5752 -- C Function: scm_inet_ntop (family, address)
5753     Convert a network address from an integer to a printable string.
5754     FAMILY can be ‘AF_INET’ or ‘AF_INET6’.  E.g.,
5755
5756          (inet-ntop AF_INET 2130706433) ⇒ "127.0.0.1"
5757          (inet-ntop AF_INET6 (- (expt 2 128) 1))
5758            ⇒ "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
5759
5760 -- Scheme Procedure: inet-pton family address
5761 -- C Function: scm_inet_pton (family, address)
5762     Convert a string containing a printable network address to an
5763     integer address.  FAMILY can be ‘AF_INET’ or ‘AF_INET6’.  E.g.,
5764
5765          (inet-pton AF_INET "127.0.0.1") ⇒ 2130706433
5766          (inet-pton AF_INET6 "::1") ⇒ 1
5767
5768
5769File: guile.info,  Node: Network Databases,  Next: Network Socket Address,  Prev: Network Address Conversion,  Up: Networking
5770
57717.2.11.2 Network Databases
5772..........................
5773
5774This section describes procedures which query various network databases.
5775Care should be taken when using the database routines since they are not
5776reentrant.
5777
5778‘getaddrinfo’
5779.............
5780
5781The ‘getaddrinfo’ procedure maps host and service names to socket
5782addresses and associated information in a protocol-independent way.
5783
5784 -- Scheme Procedure: getaddrinfo name service [hint_flags [hint_family
5785          [hint_socktype [hint_protocol]]]]
5786 -- C Function: scm_getaddrinfo (name, service, hint_flags, hint_family,
5787          hint_socktype, hint_protocol)
5788     Return a list of ‘addrinfo’ structures containing a socket address
5789     and associated information for host NAME and/or SERVICE to be used
5790     in creating a socket with which to address the specified service.
5791
5792          (let* ((ai (car (getaddrinfo "www.gnu.org" "http")))
5793                 (s  (socket (addrinfo:fam ai) (addrinfo:socktype ai)
5794                             (addrinfo:protocol ai))))
5795            (connect s (addrinfo:addr ai))
5796            s)
5797
5798     When SERVICE is omitted or is ‘#f’, return network-level addresses
5799     for NAME.  When NAME is ‘#f’ SERVICE must be provided and service
5800     locations local to the caller are returned.
5801
5802     Additional hints can be provided.  When specified, HINT_FLAGS
5803     should be a bitwise-or of zero or more constants among the
5804     following:
5805
5806     ‘AI_PASSIVE’
5807          Socket address is intended for ‘bind’.
5808
5809     ‘AI_CANONNAME’
5810          Request for canonical host name, available via
5811          ‘addrinfo:canonname’.  This makes sense mainly when DNS
5812          lookups are involved.
5813
5814     ‘AI_NUMERICHOST’
5815          Specifies that NAME is a numeric host address string (e.g.,
5816          ‘"127.0.0.1"’), meaning that name resolution will not be used.
5817
5818     ‘AI_NUMERICSERV’
5819          Likewise, specifies that SERVICE is a numeric port string
5820          (e.g., ‘"80"’).
5821
5822     ‘AI_ADDRCONFIG’
5823          Return only addresses configured on the local system It is
5824          highly recommended to provide this flag when the returned
5825          socket addresses are to be used to make connections;
5826          otherwise, some of the returned addresses could be unreachable
5827          or use a protocol that is not supported.
5828
5829     ‘AI_V4MAPPED’
5830          When looking up IPv6 addresses, return mapped IPv4 addresses
5831          if there is no IPv6 address available at all.
5832
5833     ‘AI_ALL’
5834          If this flag is set along with ‘AI_V4MAPPED’ when looking up
5835          IPv6 addresses, return all IPv6 addresses as well as all IPv4
5836          addresses, the latter mapped to IPv6 format.
5837
5838     When given, HINT_FAMILY should specify the requested address
5839     family, e.g., ‘AF_INET6’.  Similarly, HINT_SOCKTYPE should specify
5840     the requested socket type (e.g., ‘SOCK_DGRAM’), and HINT_PROTOCOL
5841     should specify the requested protocol (its value is interpreted as
5842     in calls to ‘socket’).
5843
5844     On error, an exception with key ‘getaddrinfo-error’ is thrown, with
5845     an error code (an integer) as its argument:
5846
5847          (catch 'getaddrinfo-error
5848            (lambda ()
5849              (getaddrinfo "www.gnu.org" "gopher"))
5850            (lambda (key errcode)
5851              (cond ((= errcode EAI_SERVICE)
5852          	   (display "doesn't know about Gopher!\n"))
5853          	  ((= errcode EAI_NONAME)
5854          	   (display "www.gnu.org not found\\n"))
5855          	  (else
5856          	   (format #t "something wrong: ~a\n"
5857          		   (gai-strerror errcode))))))
5858
5859     Error codes are:
5860
5861     ‘EAI_AGAIN’
5862          The name or service could not be resolved at this time.
5863          Future attempts may succeed.
5864
5865     ‘EAI_BADFLAGS’
5866          HINT_FLAGS contains an invalid value.
5867
5868     ‘EAI_FAIL’
5869          A non-recoverable error occurred when attempting to resolve
5870          the name.
5871
5872     ‘EAI_FAMILY’
5873          HINT_FAMILY was not recognized.
5874
5875     ‘EAI_NONAME’
5876          Either NAME does not resolve for the supplied parameters, or
5877          neither NAME nor SERVICE were supplied.
5878
5879     ‘EAI_NODATA’
5880          This non-POSIX error code can be returned on some systems (GNU
5881          and Darwin, at least), for example when NAME is known but
5882          requests that were made turned out no data.  Error handling
5883          code should be prepared to handle it when it is defined.
5884
5885     ‘EAI_SERVICE’
5886          SERVICE was not recognized for the specified socket type.
5887
5888     ‘EAI_SOCKTYPE’
5889          HINT_SOCKTYPE was not recognized.
5890
5891     ‘EAI_SYSTEM’
5892          A system error occurred.  In C, the error code can be found in
5893          ‘errno’; this value is not accessible from Scheme, but in
5894          practice it provides little information about the actual error
5895          cause.
5896
5897     Users are encouraged to read the "POSIX specification
5898     (http://www.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html)
5899     for more details.
5900
5901   The following procedures take an ‘addrinfo’ object as returned by
5902‘getaddrinfo’:
5903
5904 -- Scheme Procedure: addrinfo:flags ai
5905     Return flags for AI as a bitwise or of ‘AI_’ values (see above).
5906
5907 -- Scheme Procedure: addrinfo:fam ai
5908     Return the address family of AI (a ‘AF_’ value).
5909
5910 -- Scheme Procedure: addrinfo:socktype ai
5911     Return the socket type for AI (a ‘SOCK_’ value).
5912
5913 -- Scheme Procedure: addrinfo:protocol ai
5914     Return the protocol of AI.
5915
5916 -- Scheme Procedure: addrinfo:addr ai
5917     Return the socket address associated with AI as a ‘sockaddr’ object
5918     (*note Network Socket Address::).
5919
5920 -- Scheme Procedure: addrinfo:canonname ai
5921     Return a string for the canonical name associated with AI if the
5922     ‘AI_CANONNAME’ flag was supplied.
5923
5924The Host Database
5925.................
5926
5927A “host object” is a structure that represents what is known about a
5928network host, and is the usual way of representing a system’s network
5929identity inside software.
5930
5931   The following functions accept a host object and return a selected
5932component:
5933
5934 -- Scheme Procedure: hostent:name host
5935     The “official” hostname for HOST.
5936 -- Scheme Procedure: hostent:aliases host
5937     A list of aliases for HOST.
5938 -- Scheme Procedure: hostent:addrtype host
5939     The host address type, one of the ‘AF’ constants, such as ‘AF_INET’
5940     or ‘AF_INET6’.
5941 -- Scheme Procedure: hostent:length host
5942     The length of each address for HOST, in bytes.
5943 -- Scheme Procedure: hostent:addr-list host
5944     The list of network addresses associated with HOST.  For ‘AF_INET’
5945     these are integer IPv4 address (*note Network Address
5946     Conversion::).
5947
5948   The following procedures can be used to search the host database.
5949However, ‘getaddrinfo’ should be preferred over them since it’s more
5950generic and thread-safe.
5951
5952 -- Scheme Procedure: gethost [host]
5953 -- Scheme Procedure: gethostbyname hostname
5954 -- Scheme Procedure: gethostbyaddr address
5955 -- C Function: scm_gethost (host)
5956     Look up a host by name or address, returning a host object.  The
5957     ‘gethost’ procedure will accept either a string name or an integer
5958     address; if given no arguments, it behaves like ‘gethostent’ (see
5959     below).  If a name or address is supplied but the address can not
5960     be found, an error will be thrown to one of the keys:
5961     ‘host-not-found’, ‘try-again’, ‘no-recovery’ or ‘no-data’,
5962     corresponding to the equivalent ‘h_error’ values.  Unusual
5963     conditions may result in errors thrown to the ‘system-error’ or
5964     ‘misc_error’ keys.
5965
5966          (gethost "www.gnu.org")
5967          ⇒ #("www.gnu.org" () 2 4 (3353880842))
5968
5969          (gethostbyname "www.emacs.org")
5970          ⇒ #("emacs.org" ("www.emacs.org") 2 4 (1073448978))
5971
5972   The following procedures may be used to step through the host
5973database from beginning to end.
5974
5975 -- Scheme Procedure: sethostent [stayopen]
5976     Initialize an internal stream from which host objects may be read.
5977     This procedure must be called before any calls to ‘gethostent’, and
5978     may also be called afterward to reset the host entry stream.  If
5979     STAYOPEN is supplied and is not ‘#f’, the database is not closed by
5980     subsequent ‘gethostbyname’ or ‘gethostbyaddr’ calls, possibly
5981     giving an efficiency gain.
5982
5983 -- Scheme Procedure: gethostent
5984     Return the next host object from the host database, or ‘#f’ if
5985     there are no more hosts to be found (or an error has been
5986     encountered).  This procedure may not be used before ‘sethostent’
5987     has been called.
5988
5989 -- Scheme Procedure: endhostent
5990     Close the stream used by ‘gethostent’.  The return value is
5991     unspecified.
5992
5993 -- Scheme Procedure: sethost [stayopen]
5994 -- C Function: scm_sethost (stayopen)
5995     If STAYOPEN is omitted, this is equivalent to ‘endhostent’.
5996     Otherwise it is equivalent to ‘sethostent stayopen’.
5997
5998The Network Database
5999....................
6000
6001The following functions accept an object representing a network and
6002return a selected component:
6003
6004 -- Scheme Procedure: netent:name net
6005     The “official” network name.
6006 -- Scheme Procedure: netent:aliases net
6007     A list of aliases for the network.
6008 -- Scheme Procedure: netent:addrtype net
6009     The type of the network number.  Currently, this returns only
6010     ‘AF_INET’.
6011 -- Scheme Procedure: netent:net net
6012     The network number.
6013
6014   The following procedures are used to search the network database:
6015
6016 -- Scheme Procedure: getnet [net]
6017 -- Scheme Procedure: getnetbyname net-name
6018 -- Scheme Procedure: getnetbyaddr net-number
6019 -- C Function: scm_getnet (net)
6020     Look up a network by name or net number in the network database.
6021     The NET-NAME argument must be a string, and the NET-NUMBER argument
6022     must be an integer.  ‘getnet’ will accept either type of argument,
6023     behaving like ‘getnetent’ (see below) if no arguments are given.
6024
6025   The following procedures may be used to step through the network
6026database from beginning to end.
6027
6028 -- Scheme Procedure: setnetent [stayopen]
6029     Initialize an internal stream from which network objects may be
6030     read.  This procedure must be called before any calls to
6031     ‘getnetent’, and may also be called afterward to reset the net
6032     entry stream.  If STAYOPEN is supplied and is not ‘#f’, the
6033     database is not closed by subsequent ‘getnetbyname’ or
6034     ‘getnetbyaddr’ calls, possibly giving an efficiency gain.
6035
6036 -- Scheme Procedure: getnetent
6037     Return the next entry from the network database.
6038
6039 -- Scheme Procedure: endnetent
6040     Close the stream used by ‘getnetent’.  The return value is
6041     unspecified.
6042
6043 -- Scheme Procedure: setnet [stayopen]
6044 -- C Function: scm_setnet (stayopen)
6045     If STAYOPEN is omitted, this is equivalent to ‘endnetent’.
6046     Otherwise it is equivalent to ‘setnetent stayopen’.
6047
6048The Protocol Database
6049.....................
6050
6051The following functions accept an object representing a protocol and
6052return a selected component:
6053
6054 -- Scheme Procedure: protoent:name protocol
6055     The “official” protocol name.
6056 -- Scheme Procedure: protoent:aliases protocol
6057     A list of aliases for the protocol.
6058 -- Scheme Procedure: protoent:proto protocol
6059     The protocol number.
6060
6061   The following procedures are used to search the protocol database:
6062
6063 -- Scheme Procedure: getproto [protocol]
6064 -- Scheme Procedure: getprotobyname name
6065 -- Scheme Procedure: getprotobynumber number
6066 -- C Function: scm_getproto (protocol)
6067     Look up a network protocol by name or by number.  ‘getprotobyname’
6068     takes a string argument, and ‘getprotobynumber’ takes an integer
6069     argument.  ‘getproto’ will accept either type, behaving like
6070     ‘getprotoent’ (see below) if no arguments are supplied.
6071
6072   The following procedures may be used to step through the protocol
6073database from beginning to end.
6074
6075 -- Scheme Procedure: setprotoent [stayopen]
6076     Initialize an internal stream from which protocol objects may be
6077     read.  This procedure must be called before any calls to
6078     ‘getprotoent’, and may also be called afterward to reset the
6079     protocol entry stream.  If STAYOPEN is supplied and is not ‘#f’,
6080     the database is not closed by subsequent ‘getprotobyname’ or
6081     ‘getprotobynumber’ calls, possibly giving an efficiency gain.
6082
6083 -- Scheme Procedure: getprotoent
6084     Return the next entry from the protocol database.
6085
6086 -- Scheme Procedure: endprotoent
6087     Close the stream used by ‘getprotoent’.  The return value is
6088     unspecified.
6089
6090 -- Scheme Procedure: setproto [stayopen]
6091 -- C Function: scm_setproto (stayopen)
6092     If STAYOPEN is omitted, this is equivalent to ‘endprotoent’.
6093     Otherwise it is equivalent to ‘setprotoent stayopen’.
6094
6095The Service Database
6096....................
6097
6098The following functions accept an object representing a service and
6099return a selected component:
6100
6101 -- Scheme Procedure: servent:name serv
6102     The “official” name of the network service.
6103 -- Scheme Procedure: servent:aliases serv
6104     A list of aliases for the network service.
6105 -- Scheme Procedure: servent:port serv
6106     The Internet port used by the service.
6107 -- Scheme Procedure: servent:proto serv
6108     The protocol used by the service.  A service may be listed many
6109     times in the database under different protocol names.
6110
6111   The following procedures are used to search the service database:
6112
6113 -- Scheme Procedure: getserv [name [protocol]]
6114 -- Scheme Procedure: getservbyname name protocol
6115 -- Scheme Procedure: getservbyport port protocol
6116 -- C Function: scm_getserv (name, protocol)
6117     Look up a network service by name or by service number, and return
6118     a network service object.  The PROTOCOL argument specifies the name
6119     of the desired protocol; if the protocol found in the network
6120     service database does not match this name, a system error is
6121     signalled.
6122
6123     The ‘getserv’ procedure will take either a service name or number
6124     as its first argument; if given no arguments, it behaves like
6125     ‘getservent’ (see below).
6126
6127          (getserv "imap" "tcp")
6128          ⇒ #("imap2" ("imap") 143 "tcp")
6129
6130          (getservbyport 88 "udp")
6131          ⇒ #("kerberos" ("kerberos5" "krb5") 88 "udp")
6132
6133   The following procedures may be used to step through the service
6134database from beginning to end.
6135
6136 -- Scheme Procedure: setservent [stayopen]
6137     Initialize an internal stream from which service objects may be
6138     read.  This procedure must be called before any calls to
6139     ‘getservent’, and may also be called afterward to reset the service
6140     entry stream.  If STAYOPEN is supplied and is not ‘#f’, the
6141     database is not closed by subsequent ‘getservbyname’ or
6142     ‘getservbyport’ calls, possibly giving an efficiency gain.
6143
6144 -- Scheme Procedure: getservent
6145     Return the next entry from the services database.
6146
6147 -- Scheme Procedure: endservent
6148     Close the stream used by ‘getservent’.  The return value is
6149     unspecified.
6150
6151 -- Scheme Procedure: setserv [stayopen]
6152 -- C Function: scm_setserv (stayopen)
6153     If STAYOPEN is omitted, this is equivalent to ‘endservent’.
6154     Otherwise it is equivalent to ‘setservent stayopen’.
6155
6156
6157File: guile.info,  Node: Network Socket Address,  Next: Network Sockets and Communication,  Prev: Network Databases,  Up: Networking
6158
61597.2.11.3 Network Socket Address
6160...............................
6161
6162A “socket address” object identifies a socket endpoint for
6163communication.  In the case of ‘AF_INET’ for instance, the socket
6164address object comprises the host address (or interface on the host) and
6165a port number which specifies a particular open socket in a running
6166client or server process.  A socket address object can be created with,
6167
6168 -- Scheme Procedure: make-socket-address AF_INET ipv4addr port
6169 -- Scheme Procedure: make-socket-address AF_INET6 ipv6addr port
6170          [flowinfo [scopeid]]
6171 -- Scheme Procedure: make-socket-address AF_UNIX path
6172 -- C Function: scm_make_socket_address (family, address, arglist)
6173     Return a new socket address object.  The first argument is the
6174     address family, one of the ‘AF’ constants, then the arguments vary
6175     according to the family.
6176
6177     For ‘AF_INET’ the arguments are an IPv4 network address number
6178     (*note Network Address Conversion::), and a port number.
6179
6180     For ‘AF_INET6’ the arguments are an IPv6 network address number and
6181     a port number.  Optional FLOWINFO and SCOPEID arguments may be
6182     given (both integers, default 0).
6183
6184     For ‘AF_UNIX’ the argument is a filename (a string).
6185
6186     The C function ‘scm_make_socket_address’ takes the FAMILY and
6187     ADDRESS arguments directly, then ARGLIST is a list of further
6188     arguments, being the port for IPv4, port and optional flowinfo and
6189     scopeid for IPv6, or the empty list ‘SCM_EOL’ for Unix domain.
6190
6191The following functions access the fields of a socket address object,
6192
6193 -- Scheme Procedure: sockaddr:fam sa
6194     Return the address family from socket address object SA.  This is
6195     one of the ‘AF’ constants (e.g. ‘AF_INET’).
6196
6197 -- Scheme Procedure: sockaddr:path sa
6198     For an ‘AF_UNIX’ socket address object SA, return the filename.
6199
6200 -- Scheme Procedure: sockaddr:addr sa
6201     For an ‘AF_INET’ or ‘AF_INET6’ socket address object SA, return the
6202     network address number.
6203
6204 -- Scheme Procedure: sockaddr:port sa
6205     For an ‘AF_INET’ or ‘AF_INET6’ socket address object SA, return the
6206     port number.
6207
6208 -- Scheme Procedure: sockaddr:flowinfo sa
6209     For an ‘AF_INET6’ socket address object SA, return the flowinfo
6210     value.
6211
6212 -- Scheme Procedure: sockaddr:scopeid sa
6213     For an ‘AF_INET6’ socket address object SA, return the scope ID
6214     value.
6215
6216   The functions below convert to and from the C ‘struct sockaddr’
6217(*note (libc)Address Formats::).  That structure is a generic type, an
6218application can cast to or from ‘struct sockaddr_in’, ‘struct
6219sockaddr_in6’ or ‘struct sockaddr_un’ according to the address family.
6220
6221   In a ‘struct sockaddr’ taken or returned, the byte ordering in the
6222fields follows the C conventions (*note Byte Order Conversion:
6223(libc)Byte Order.).  This means network byte order for ‘AF_INET’ host
6224address (‘sin_addr.s_addr’) and port number (‘sin_port’), and ‘AF_INET6’
6225port number (‘sin6_port’).  But at the Scheme level these values are
6226taken or returned in host byte order, so the port is an ordinary
6227integer, and the host address likewise is an ordinary integer (as
6228described in *note Network Address Conversion::).
6229
6230 -- C Function: struct sockaddr * scm_c_make_socket_address (SCM family,
6231          SCM address, SCM args, size_t *outsize)
6232     Return a newly-‘malloc’ed ‘struct sockaddr’ created from arguments
6233     like those taken by ‘scm_make_socket_address’ above.
6234
6235     The size (in bytes) of the ‘struct sockaddr’ return is stored into
6236     ‘*OUTSIZE’.  An application must call ‘free’ to release the
6237     returned structure when no longer required.
6238
6239 -- C Function: SCM scm_from_sockaddr (const struct sockaddr *address,
6240          unsigned address_size)
6241     Return a Scheme socket address object from the C ADDRESS structure.
6242     ADDRESS_SIZE is the size in bytes of ADDRESS.
6243
6244 -- C Function: struct sockaddr * scm_to_sockaddr (SCM address, size_t
6245          *address_size)
6246     Return a newly-‘malloc’ed ‘struct sockaddr’ from a Scheme level
6247     socket address object.
6248
6249     The size (in bytes) of the ‘struct sockaddr’ return is stored into
6250     ‘*OUTSIZE’.  An application must call ‘free’ to release the
6251     returned structure when no longer required.
6252
6253
6254File: guile.info,  Node: Network Sockets and Communication,  Next: Internet Socket Examples,  Prev: Network Socket Address,  Up: Networking
6255
62567.2.11.4 Network Sockets and Communication
6257..........................................
6258
6259Socket ports can be created using ‘socket’ and ‘socketpair’.  The ports
6260are initially unbuffered, to make reading and writing to the same port
6261more reliable.  A buffer can be added to the port using ‘setvbuf’ (*note
6262Buffering::).
6263
6264   Most systems have limits on how many files and sockets can be open,
6265so it’s strongly recommended that socket ports be closed explicitly when
6266no longer required (*note Ports::).
6267
6268   Some of the underlying C functions take values in network byte order,
6269but the convention in Guile is that at the Scheme level everything is
6270ordinary host byte order and conversions are made automatically where
6271necessary.
6272
6273 -- Scheme Procedure: socket family style proto
6274 -- C Function: scm_socket (family, style, proto)
6275     Return a new socket port of the type specified by FAMILY, STYLE and
6276     PROTO.  All three parameters are integers.  The possible values for
6277     FAMILY are as follows, where supported by the system,
6278
6279      -- Variable: PF_UNIX
6280      -- Variable: PF_INET
6281      -- Variable: PF_INET6
6282
6283     The possible values for STYLE are as follows, again where supported
6284     by the system,
6285
6286      -- Variable: SOCK_STREAM
6287      -- Variable: SOCK_DGRAM
6288      -- Variable: SOCK_RAW
6289      -- Variable: SOCK_RDM
6290      -- Variable: SOCK_SEQPACKET
6291
6292     PROTO can be obtained from a protocol name using ‘getprotobyname’
6293     (*note Network Databases::).  A value of zero means the default
6294     protocol, which is usually right.
6295
6296     A socket cannot by used for communication until it has been
6297     connected somewhere, usually with either ‘connect’ or ‘accept’
6298     below.
6299
6300 -- Scheme Procedure: socketpair family style proto
6301 -- C Function: scm_socketpair (family, style, proto)
6302     Return a pair, the ‘car’ and ‘cdr’ of which are two unnamed socket
6303     ports connected to each other.  The connection is full-duplex, so
6304     data can be transferred in either direction between the two.
6305
6306     FAMILY, STYLE and PROTO are as per ‘socket’ above.  But many
6307     systems only support socket pairs in the ‘PF_UNIX’ family.  Zero is
6308     likely to be the only meaningful value for PROTO.
6309
6310 -- Scheme Procedure: getsockopt sock level optname
6311 -- Scheme Procedure: setsockopt sock level optname value
6312 -- C Function: scm_getsockopt (sock, level, optname)
6313 -- C Function: scm_setsockopt (sock, level, optname, value)
6314     Get or set an option on socket port SOCK.  ‘getsockopt’ returns the
6315     current value.  ‘setsockopt’ sets a value and the return is
6316     unspecified.
6317
6318     LEVEL is an integer specifying a protocol layer, either
6319     ‘SOL_SOCKET’ for socket level options, or a protocol number from
6320     the ‘IPPROTO’ constants or ‘getprotoent’ (*note Network
6321     Databases::).
6322
6323      -- Variable: SOL_SOCKET
6324      -- Variable: IPPROTO_IP
6325      -- Variable: IPPROTO_TCP
6326      -- Variable: IPPROTO_UDP
6327
6328     OPTNAME is an integer specifying an option within the protocol
6329     layer.
6330
6331     For ‘SOL_SOCKET’ level the following OPTNAMEs are defined (when
6332     provided by the system).  For their meaning see *note
6333     (libc)Socket-Level Options::, or ‘man 7 socket’.
6334
6335      -- Variable: SO_DEBUG
6336      -- Variable: SO_REUSEADDR
6337      -- Variable: SO_STYLE
6338      -- Variable: SO_TYPE
6339      -- Variable: SO_ERROR
6340      -- Variable: SO_DONTROUTE
6341      -- Variable: SO_BROADCAST
6342      -- Variable: SO_SNDBUF
6343      -- Variable: SO_RCVBUF
6344      -- Variable: SO_KEEPALIVE
6345      -- Variable: SO_OOBINLINE
6346      -- Variable: SO_NO_CHECK
6347      -- Variable: SO_PRIORITY
6348      -- Variable: SO_REUSEPORT
6349          The VALUE taken or returned is an integer.
6350
6351      -- Variable: SO_LINGER
6352          The VALUE taken or returned is a pair of integers ‘(ENABLE .
6353          TIMEOUT)’.  On old systems without timeout support (ie.
6354          without ‘struct linger’), only ENABLE has an effect but the
6355          value in Guile is always a pair.
6356
6357     For IP level (‘IPPROTO_IP’) the following OPTNAMEs are defined
6358     (when provided by the system).  See ‘man ip’ for what they mean.
6359
6360      -- Variable: IP_MULTICAST_IF
6361          This sets the source interface used by multicast traffic.
6362
6363      -- Variable: IP_MULTICAST_TTL
6364          This sets the default TTL for multicast traffic.  This
6365          defaults to 1 and should be increased to allow traffic to pass
6366          beyond the local network.
6367
6368      -- Variable: IP_ADD_MEMBERSHIP
6369      -- Variable: IP_DROP_MEMBERSHIP
6370          These can be used only with ‘setsockopt’, not ‘getsockopt’.
6371          VALUE is a pair ‘(MULTIADDR . INTERFACEADDR)’ of integer IPv4
6372          addresses (*note Network Address Conversion::).  MULTIADDR is
6373          a multicast address to be added to or dropped from the
6374          interface INTERFACEADDR.  INTERFACEADDR can be ‘INADDR_ANY’ to
6375          have the system select the interface.  INTERFACEADDR can also
6376          be an interface index number, on systems supporting that.
6377
6378   For ‘IPPROTO_TCP’ level the following OPTNAMEs are defined (when
6379provided by the system).  For their meaning see ‘man 7 tcp’.
6380
6381 -- Variable: TCP_NODELAY
6382 -- Variable: TCP_CORK
6383     The VALUE taken or returned is an integer.
6384
6385 -- Scheme Procedure: shutdown sock how
6386 -- C Function: scm_shutdown (sock, how)
6387     Sockets can be closed simply by using ‘close-port’.  The ‘shutdown’
6388     procedure allows reception or transmission on a connection to be
6389     shut down individually, according to the parameter HOW:
6390
6391     0
6392          Stop receiving data for this socket.  If further data arrives,
6393          reject it.
6394     1
6395          Stop trying to transmit data from this socket.  Discard any
6396          data waiting to be sent.  Stop looking for acknowledgement of
6397          data already sent; don’t retransmit it if it is lost.
6398     2
6399          Stop both reception and transmission.
6400
6401     The return value is unspecified.
6402
6403 -- Scheme Procedure: connect sock sockaddr
6404 -- Scheme Procedure: connect sock AF_INET ipv4addr port
6405 -- Scheme Procedure: connect sock AF_INET6 ipv6addr port [flowinfo
6406          [scopeid]]
6407 -- Scheme Procedure: connect sock AF_UNIX path
6408 -- C Function: scm_connect (sock, fam, address, args)
6409     Initiate a connection on socket port SOCK to a given address.  The
6410     destination is either a socket address object, or arguments the
6411     same as ‘make-socket-address’ would take to make such an object
6412     (*note Network Socket Address::).  Return true unless the socket
6413     was configured as non-blocking and the connection could not be made
6414     immediately.
6415
6416          (connect sock AF_INET INADDR_LOOPBACK 23)
6417          (connect sock (make-socket-address AF_INET INADDR_LOOPBACK 23))
6418
6419 -- Scheme Procedure: bind sock sockaddr
6420 -- Scheme Procedure: bind sock AF_INET ipv4addr port
6421 -- Scheme Procedure: bind sock AF_INET6 ipv6addr port [flowinfo
6422          [scopeid]]
6423 -- Scheme Procedure: bind sock AF_UNIX path
6424 -- C Function: scm_bind (sock, fam, address, args)
6425     Bind socket port SOCK to the given address.  The address is either
6426     a socket address object, or arguments the same as
6427     ‘make-socket-address’ would take to make such an object (*note
6428     Network Socket Address::).  The return value is unspecified.
6429
6430     Generally a socket is only explicitly bound to a particular address
6431     when making a server, i.e. to listen on a particular port.  For an
6432     outgoing connection the system will assign a local address
6433     automatically, if not already bound.
6434
6435          (bind sock AF_INET INADDR_ANY 12345)
6436          (bind sock (make-socket-address AF_INET INADDR_ANY 12345))
6437
6438 -- Scheme Procedure: listen sock backlog
6439 -- C Function: scm_listen (sock, backlog)
6440     Enable SOCK to accept connection requests.  BACKLOG is an integer
6441     specifying the maximum length of the queue for pending connections.
6442     If the queue fills, new clients will fail to connect until the
6443     server calls ‘accept’ to accept a connection from the queue.
6444
6445     The return value is unspecified.
6446
6447 -- Scheme Procedure: accept sock [flags]
6448 -- C Function: scm_accept (sock)
6449     Accept a connection from socket port SOCK which has been enabled
6450     for listening with ‘listen’ above.
6451
6452     If there are no incoming connections in the queue, there are two
6453     possible behaviors, depending on whether SOCK has been configured
6454     for non-blocking operation or not:
6455
6456        • If there is no connection waiting and the socket was set to
6457          non-blocking mode with the ‘O_NONBLOCK’ port option (*note
6458          ‘fcntl’: Ports and File Descriptors.), return ‘#f’ directly.
6459
6460        • Otherwise wait until a connection is available.
6461
6462     The return value is a pair.  The ‘car’ is a new socket port,
6463     connected and ready to communicate.  The ‘cdr’ is a socket address
6464     object (*note Network Socket Address::) which is where the remote
6465     connection is from (like ‘getpeername’ below).
6466
6467     FLAGS, if given, may include ‘SOCK_CLOEXEC’ or ‘SOCK_NONBLOCK’,
6468     which like ‘O_CLOEXEC’ and ‘O_NONBLOCK’ apply to the newly accepted
6469     socket.
6470
6471     All communication takes place using the new socket returned.  The
6472     given SOCK remains bound and listening, and ‘accept’ may be called
6473     on it again to get another incoming connection when desired.
6474
6475 -- Scheme Procedure: getsockname sock
6476 -- C Function: scm_getsockname (sock)
6477     Return a socket address object which is the where SOCK is bound
6478     locally.  SOCK may have obtained its local address from ‘bind’
6479     (above), or if a ‘connect’ is done with an otherwise unbound socket
6480     (which is usual) then the system will have assigned an address.
6481
6482     Note that on many systems the address of a socket in the ‘AF_UNIX’
6483     namespace cannot be read.
6484
6485 -- Scheme Procedure: getpeername sock
6486 -- C Function: scm_getpeername (sock)
6487     Return a socket address object which is where SOCK is connected to,
6488     i.e. the remote endpoint.
6489
6490     Note that on many systems the address of a socket in the ‘AF_UNIX’
6491     namespace cannot be read.
6492
6493 -- Scheme Procedure: recv! sock buf [flags]
6494 -- C Function: scm_recv (sock, buf, flags)
6495     Receive data from a socket port.  SOCK must already be bound to the
6496     address from which data is to be received.  BUF is a bytevector
6497     into which the data will be written.  The size of BUF limits the
6498     amount of data which can be received: in the case of packet
6499     protocols, if a packet larger than this limit is encountered then
6500     some data will be irrevocably lost.
6501
6502     The optional FLAGS argument is a value or bitwise OR of ‘MSG_OOB’,
6503     ‘MSG_PEEK’, ‘MSG_DONTROUTE’ etc.
6504
6505     The value returned is the number of bytes read from the socket.
6506
6507     Note that the data is read directly from the socket file
6508     descriptor: any unread buffered port data is ignored.
6509
6510 -- Scheme Procedure: send sock message [flags]
6511 -- C Function: scm_send (sock, message, flags)
6512     Transmit bytevector MESSAGE on socket port SOCK.  SOCK must already
6513     be bound to a destination address.  The value returned is the
6514     number of bytes transmitted—it’s possible for this to be less than
6515     the length of MESSAGE if the socket is set to be non-blocking.  The
6516     optional FLAGS argument is a value or bitwise OR of ‘MSG_OOB’,
6517     ‘MSG_PEEK’, ‘MSG_DONTROUTE’ etc.
6518
6519     Note that the data is written directly to the socket file
6520     descriptor: any unflushed buffered port data is ignored.
6521
6522 -- Scheme Procedure: recvfrom! sock buf [flags [start [end]]]
6523 -- C Function: scm_recvfrom (sock, buf, flags, start, end)
6524     Receive data from socket port SOCK, returning the originating
6525     address as well as the data.  This function is usually for datagram
6526     sockets, but can be used on stream-oriented sockets too.
6527
6528     The data received is stored in bytevector BUF, using either the
6529     whole bytevector or just the region between the optional START and
6530     END positions.  The size of BUF limits the amount of data that can
6531     be received.  For datagram protocols if a packet larger than this
6532     is received then excess bytes are irrevocably lost.
6533
6534     The return value is a pair.  The ‘car’ is the number of bytes read.
6535     The ‘cdr’ is a socket address object (*note Network Socket
6536     Address::) which is where the data came from, or ‘#f’ if the origin
6537     is unknown.
6538
6539     The optional FLAGS argument is a or bitwise-OR (‘logior’) of
6540     ‘MSG_OOB’, ‘MSG_PEEK’, ‘MSG_DONTROUTE’ etc.
6541
6542     Data is read directly from the socket file descriptor, any buffered
6543     port data is ignored.
6544
6545     On a GNU/Linux system ‘recvfrom!’ is not multi-threading, all
6546     threads stop while a ‘recvfrom!’ call is in progress.  An
6547     application may need to use ‘select’, ‘O_NONBLOCK’ or
6548     ‘MSG_DONTWAIT’ to avoid this.
6549
6550 -- Scheme Procedure: sendto sock message sockaddr [flags]
6551 -- Scheme Procedure: sendto sock message AF_INET ipv4addr port [flags]
6552 -- Scheme Procedure: sendto sock message AF_INET6 ipv6addr port
6553          [flowinfo [scopeid [flags]]]
6554 -- Scheme Procedure: sendto sock message AF_UNIX path [flags]
6555 -- C Function: scm_sendto (sock, message, fam, address, args_and_flags)
6556     Transmit bytevector MESSAGE as a datagram socket port SOCK.  The
6557     destination is specified either as a socket address object, or as
6558     arguments the same as would be taken by ‘make-socket-address’ to
6559     create such an object (*note Network Socket Address::).
6560
6561     The destination address may be followed by an optional FLAGS
6562     argument which is a ‘logior’ (*note Bitwise Operations::) of
6563     ‘MSG_OOB’, ‘MSG_PEEK’, ‘MSG_DONTROUTE’ etc.
6564
6565     The value returned is the number of bytes transmitted – it’s
6566     possible for this to be less than the length of MESSAGE if the
6567     socket is set to be non-blocking.  Note that the data is written
6568     directly to the socket file descriptor: any unflushed buffered port
6569     data is ignored.
6570
6571
6572File: guile.info,  Node: Internet Socket Examples,  Prev: Network Sockets and Communication,  Up: Networking
6573
65747.2.11.5 Network Socket Examples
6575................................
6576
6577The following give examples of how to use network sockets.
6578
6579Internet Socket Client Example
6580..............................
6581
6582The following example demonstrates an Internet socket client.  It
6583connects to the HTTP daemon running on the local machine and returns the
6584contents of the root index URL.
6585
6586     (let ((s (socket PF_INET SOCK_STREAM 0)))
6587       (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 80)
6588       (display "GET / HTTP/1.0\r\n\r\n" s)
6589
6590       (do ((line (read-line s) (read-line s)))
6591           ((eof-object? line))
6592         (display line)
6593         (newline)))
6594
6595Internet Socket Server Example
6596..............................
6597
6598The following example shows a simple Internet server which listens on
6599port 2904 for incoming connections and sends a greeting back to the
6600client.
6601
6602     (let ((s (socket PF_INET SOCK_STREAM 0)))
6603       (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
6604       ;; Specific address?
6605       ;; (bind s AF_INET (inet-pton AF_INET "127.0.0.1") 2904)
6606       (bind s AF_INET INADDR_ANY 2904)
6607       (listen s 5)
6608
6609       (simple-format #t "Listening for clients in pid: ~S" (getpid))
6610       (newline)
6611
6612       (while #t
6613         (let* ((client-connection (accept s))
6614                (client-details (cdr client-connection))
6615                (client (car client-connection)))
6616           (simple-format #t "Got new client connection: ~S"
6617                          client-details)
6618           (newline)
6619           (simple-format #t "Client address: ~S"
6620                          (gethostbyaddr
6621                           (sockaddr:addr client-details)))
6622           (newline)
6623           ;; Send back the greeting to the client port
6624           (display "Hello client\r\n" client)
6625           (close client))))
6626
6627
6628File: guile.info,  Node: System Identification,  Next: Locales,  Prev: Networking,  Up: POSIX
6629
66307.2.12 System Identification
6631----------------------------
6632
6633This section lists the various procedures Guile provides for accessing
6634information about the system it runs on.
6635
6636 -- Scheme Procedure: uname
6637 -- C Function: scm_uname ()
6638     Return an object with some information about the computer system
6639     the program is running on.
6640
6641     The following procedures accept an object as returned by ‘uname’
6642     and return a selected component (all of which are strings).
6643
6644      -- Scheme Procedure: utsname:sysname un
6645          The name of the operating system.
6646      -- Scheme Procedure: utsname:nodename un
6647          The network name of the computer.
6648      -- Scheme Procedure: utsname:release un
6649          The current release level of the operating system
6650          implementation.
6651      -- Scheme Procedure: utsname:version un
6652          The current version level within the release of the operating
6653          system.
6654      -- Scheme Procedure: utsname:machine un
6655          A description of the hardware.
6656
6657 -- Scheme Procedure: gethostname
6658 -- C Function: scm_gethostname ()
6659     Return the host name of the current processor.
6660
6661 -- Scheme Procedure: sethostname name
6662 -- C Function: scm_sethostname (name)
6663     Set the host name of the current processor to NAME.  May only be
6664     used by the superuser.  The return value is not specified.
6665
6666
6667File: guile.info,  Node: Locales,  Next: Encryption,  Prev: System Identification,  Up: POSIX
6668
66697.2.13 Locales
6670--------------
6671
6672 -- Scheme Procedure: setlocale category [locale]
6673 -- C Function: scm_setlocale (category, locale)
6674     Get or set the current locale, used for various
6675     internationalizations.  Locales are strings, such as ‘sv_SE’.
6676
6677     If LOCALE is given then the locale for the given CATEGORY is set
6678     and the new value returned.  If LOCALE is not given then the
6679     current value is returned.  CATEGORY should be one of the following
6680     values (*note Categories of Activities that Locales Affect:
6681     (libc)Locale Categories.):
6682
6683      -- Variable: LC_ALL
6684      -- Variable: LC_COLLATE
6685      -- Variable: LC_CTYPE
6686      -- Variable: LC_MESSAGES
6687      -- Variable: LC_MONETARY
6688      -- Variable: LC_NUMERIC
6689      -- Variable: LC_TIME
6690
6691     A common usage is ‘(setlocale LC_ALL "")’, which initializes all
6692     categories based on standard environment variables (‘LANG’ etc).
6693     For full details on categories and locale names *note Locales and
6694     Internationalization: (libc)Locales.
6695
6696     Note that ‘setlocale’ affects locale settings for the whole
6697     process.  *Note locale objects and ‘make-locale’: i18n
6698     Introduction, for a thread-safe alternative.
6699
6700
6701File: guile.info,  Node: Encryption,  Prev: Locales,  Up: POSIX
6702
67037.2.14 Encryption
6704-----------------
6705
6706Please note that the procedures in this section are not suited for
6707strong encryption, they are only interfaces to the well-known and common
6708system library functions of the same name.  They are just as good (or
6709bad) as the underlying functions, so you should refer to your system
6710documentation before using them (*note Encrypting Passwords:
6711(libc)crypt.).
6712
6713 -- Scheme Procedure: crypt key salt
6714 -- C Function: scm_crypt (key, salt)
6715     Encrypt KEY, with the addition of SALT (both strings), using the
6716     ‘crypt’ C library call.
6717
6718   Although ‘getpass’ is not an encryption procedure per se, it appears
6719here because it is often used in combination with ‘crypt’:
6720
6721 -- Scheme Procedure: getpass prompt
6722 -- C Function: scm_getpass (prompt)
6723     Display PROMPT to the standard error output and read a password
6724     from ‘/dev/tty’.  If this file is not accessible, it reads from
6725     standard input.  The password may be up to 127 characters in
6726     length.  Additional characters and the terminating newline
6727     character are discarded.  While reading the password, echoing and
6728     the generation of signals by special characters is disabled.
6729
6730
6731File: guile.info,  Node: Web,  Next: getopt-long,  Prev: POSIX,  Up: Guile Modules
6732
67337.3 HTTP, the Web, and All That
6734===============================
6735
6736It has always been possible to connect computers together and share
6737information between them, but the rise of the World Wide Web over the
6738last couple of decades has made it much easier to do so.  The result is
6739a richly connected network of computation, in which Guile forms a part.
6740
6741   By “the web”, we mean the HTTP protocol(1) as handled by servers,
6742clients, proxies, caches, and the various kinds of messages and message
6743components that can be sent and received by that protocol, notably HTML.
6744
6745   On one level, the web is text in motion: the protocols themselves are
6746textual (though the payload may be binary), and it’s possible to create
6747a socket and speak text to the web.  But such an approach is obviously
6748primitive.  This section details the higher-level data types and
6749operations provided by Guile: URIs, HTTP request and response records,
6750and a conventional web server implementation.
6751
6752   The material in this section is arranged in ascending order, in which
6753later concepts build on previous ones.  If you prefer to start with the
6754highest-level perspective, *note Web Examples::, and work your way back.
6755
6756* Menu:
6757
6758* Types and the Web::           Types prevent bugs and security problems.
6759* URIs::                        Universal Resource Identifiers.
6760* HTTP::                        The Hyper-Text Transfer Protocol.
6761* HTTP Headers::                How Guile represents specific header values.
6762* Transfer Codings::            HTTP Transfer Codings.
6763* Requests::                    HTTP requests.
6764* Responses::                   HTTP responses.
6765* Web Client::                  Accessing web resources over HTTP.
6766* Web Server::                  Serving HTTP to the internet.
6767* Web Examples::                How to use this thing.
6768
6769   ---------- Footnotes ----------
6770
6771   (1) Yes, the P is for protocol, but this phrase appears repeatedly in
6772RFC 2616.
6773
6774
6775File: guile.info,  Node: Types and the Web,  Next: URIs,  Up: Web
6776
67777.3.1 Types and the Web
6778-----------------------
6779
6780It is a truth universally acknowledged, that a program with good use of
6781data types, will be free from many common bugs.  Unfortunately, the
6782common practice in web programming seems to ignore this maxim.  This
6783subsection makes the case for expressive data types in web programming.
6784
6785   By “expressive data types”, we mean that the data types _say_
6786something about how a program solves a problem.  For example, if we
6787choose to represent dates using SRFI 19 date records (*note SRFI-19::),
6788this indicates that there is a part of the program that will always have
6789valid dates.  Error handling for a number of basic cases, like invalid
6790dates, occurs on the boundary in which we produce a SRFI 19 date record
6791from other types, like strings.
6792
6793   With regards to the web, data types are helpful in the two broad
6794phases of HTTP messages: parsing and generation.
6795
6796   Consider a server, which has to parse a request, and produce a
6797response.  Guile will parse the request into an HTTP request object
6798(*note Requests::), with each header parsed into an appropriate Scheme
6799data type.  This transition from an incoming stream of characters to
6800typed data is a state change in a program—the strings might parse, or
6801they might not, and something has to happen if they do not.  (Guile
6802throws an error in this case.)  But after you have the parsed request,
6803“client” code (code built on top of the Guile web framework) will not
6804have to check for syntactic validity.  The types already make this
6805information manifest.
6806
6807   This state change on the parsing boundary makes programs more robust,
6808as they themselves are freed from the need to do a number of common
6809error checks, and they can use normal Scheme procedures to handle a
6810request instead of ad-hoc string parsers.
6811
6812   The need for types on the response generation side (in a server) is
6813more subtle, though not less important.  Consider the example of a POST
6814handler, which prints out the text that a user submits from a form.
6815Such a handler might include a procedure like this:
6816
6817     ;; First, a helper procedure
6818     (define (para . contents)
6819       (string-append "<p>" (string-concatenate contents) "</p>"))
6820
6821     ;; Now the meat of our simple web application
6822     (define (you-said text)
6823       (para "You said: " text))
6824
6825     (display (you-said "Hi!"))
6826     ⊣ <p>You said: Hi!</p>
6827
6828   This is a perfectly valid implementation, provided that the incoming
6829text does not contain the special HTML characters ‘<’, ‘>’, or ‘&’.  But
6830this provision of a restricted character set is not reflected anywhere
6831in the program itself: we must _assume_ that the programmer understands
6832this, and performs the check elsewhere.
6833
6834   Unfortunately, the short history of the practice of programming does
6835not bear out this assumption.  A “cross-site scripting” (XSS)
6836vulnerability is just such a common error in which unfiltered user input
6837is allowed into the output.  A user could submit a crafted comment to
6838your web site which results in visitors running malicious Javascript,
6839within the security context of your domain:
6840
6841     (display (you-said "<script src=\"http://bad.com/nasty.js\" />"))
6842     ⊣ <p>You said: <script src="http://bad.com/nasty.js" /></p>
6843
6844   The fundamental problem here is that both user data and the program
6845template are represented using strings.  This identity means that types
6846can’t help the programmer to make a distinction between these two, so
6847they get confused.
6848
6849   There are a number of possible solutions, but perhaps the best is to
6850treat HTML not as strings, but as native s-expressions: as SXML. The
6851basic idea is that HTML is either text, represented by a string, or an
6852element, represented as a tagged list.  So ‘foo’ becomes ‘"foo"’, and
6853‘<b>foo</b>’ becomes ‘(b "foo")’.  Attributes, if present, go in a
6854tagged list headed by ‘@’, like ‘(img (@ (src
6855"http://example.com/foo.png")))’.  *Note SXML::, for more information.
6856
6857   The good thing about SXML is that HTML elements cannot be confused
6858with text.  Let’s make a new definition of ‘para’:
6859
6860     (define (para . contents)
6861       `(p ,@contents))
6862
6863     (use-modules (sxml simple))
6864     (sxml->xml (you-said "Hi!"))
6865     ⊣ <p>You said: Hi!</p>
6866
6867     (sxml->xml (you-said "<i>Rats, foiled again!</i>"))
6868     ⊣ <p>You said: &lt;i&gt;Rats, foiled again!&lt;/i&gt;</p>
6869
6870   So we see in the second example that HTML elements cannot be
6871unwittingly introduced into the output.  However it is now perfectly
6872acceptable to pass SXML to ‘you-said’; in fact, that is the big
6873advantage of SXML over everything-as-a-string.
6874
6875     (sxml->xml (you-said (you-said "<Hi!>")))
6876     ⊣ <p>You said: <p>You said: &lt;Hi!&gt;</p></p>
6877
6878   The SXML types allow procedures to _compose_.  The types make
6879manifest which parts are HTML elements, and which are text.  So you
6880needn’t worry about escaping user input; the type transition back to a
6881string handles that for you.  XSS vulnerabilities are a thing of the
6882past.
6883
6884   Well.  That’s all very nice and opinionated and such, but how do I
6885use the thing?  Read on!
6886
6887