doc: Warn against misuses of `file-name-separator-string'.
[bpt/guile.git] / doc / ref / posix.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007,
4 @c 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node POSIX
8 @section @acronym{POSIX} System Calls and Networking
9 @cindex POSIX
10
11 @menu
12 * Conventions:: Conventions employed by the POSIX interface.
13 * Ports and File Descriptors:: Scheme ``ports'' and Unix file descriptors
14 have different representations.
15 * File System:: stat, chown, chmod, etc.
16 * User Information:: Retrieving a user's GECOS (/etc/passwd) entry.
17 * Time:: gettimeofday, localtime, strftime, etc.
18 * Runtime Environment:: Accessing and modifying Guile's environment.
19 * Processes:: getuid, getpid, etc.
20 * Signals:: sigaction, kill, pause, alarm, setitimer, etc.
21 * Terminals and Ptys:: ttyname, tcsetpgrp, etc.
22 * Pipes:: Communicating data between processes.
23 * Networking:: gethostbyaddr, getnetent, socket, bind, listen.
24 * System Identification:: Obtaining information about the system.
25 * Locales:: setlocale, etc.
26 * Encryption::
27 @end menu
28
29 @node Conventions
30 @subsection @acronym{POSIX} Interface Conventions
31
32 These interfaces provide access to operating system facilities.
33 They provide a simple wrapping around the underlying C interfaces
34 to make usage from Scheme more convenient. They are also used
35 to implement the Guile port of scsh (@pxref{The Scheme shell (scsh)}).
36
37 Generally there is a single procedure for each corresponding Unix
38 facility. There are some exceptions, such as procedures implemented for
39 speed and convenience in Scheme with no primitive Unix equivalent,
40 e.g.@: @code{copy-file}.
41
42 The interfaces are intended as far as possible to be portable across
43 different versions of Unix. In some cases procedures which can't be
44 implemented on particular systems may become no-ops, or perform limited
45 actions. In other cases they may throw errors.
46
47 General naming conventions are as follows:
48
49 @itemize @bullet
50 @item
51 The Scheme name is often identical to the name of the underlying Unix
52 facility.
53 @item
54 Underscores in Unix procedure names are converted to hyphens.
55 @item
56 Procedures which destructively modify Scheme data have exclamation
57 marks appended, e.g., @code{recv!}.
58 @item
59 Predicates (returning only @code{#t} or @code{#f}) have question marks
60 appended, e.g., @code{access?}.
61 @item
62 Some names are changed to avoid conflict with dissimilar interfaces
63 defined by scsh, e.g., @code{primitive-fork}.
64 @item
65 Unix preprocessor names such as @code{EPERM} or @code{R_OK} are converted
66 to Scheme variables of the same name (underscores are not replaced
67 with hyphens).
68 @end itemize
69
70 Unexpected conditions are generally handled by raising exceptions.
71 There are a few procedures which return a special value if they don't
72 succeed, e.g., @code{getenv} returns @code{#f} if it the requested
73 string is not found in the environment. These cases are noted in
74 the documentation.
75
76 For ways to deal with exceptions, see @ref{Exceptions}.
77
78 @cindex @code{errno}
79 Errors which the C library would report by returning a null pointer or
80 through some other means are reported by raising a @code{system-error}
81 exception with @code{scm-error} (@pxref{Error Reporting}). The
82 @var{data} parameter is a list containing the Unix @code{errno} value
83 (an integer). For example,
84
85 @example
86 (define (my-handler key func fmt fmtargs data)
87 (display key) (newline)
88 (display func) (newline)
89 (apply format #t fmt fmtargs) (newline)
90 (display data) (newline))
91
92 (catch 'system-error
93 (lambda () (dup2 -123 -456))
94 my-handler)
95
96 @print{}
97 system-error
98 dup2
99 Bad file descriptor
100 (9)
101 @end example
102
103
104 @sp 1
105 @defun system-error-errno arglist
106 @cindex @code{errno}
107 Return the @code{errno} value from a list which is the arguments to an
108 exception handler. If the exception is not a @code{system-error},
109 then the return is @code{#f}. For example,
110
111 @example
112 (catch
113 'system-error
114 (lambda ()
115 (mkdir "/this-ought-to-fail-if-I'm-not-root"))
116 (lambda stuff
117 (let ((errno (system-error-errno stuff)))
118 (cond
119 ((= errno EACCES)
120 (display "You're not allowed to do that."))
121 ((= errno EEXIST)
122 (display "Already exists."))
123 (#t
124 (display (strerror errno))))
125 (newline))))
126 @end example
127 @end defun
128
129
130 @node Ports and File Descriptors
131 @subsection Ports and File Descriptors
132 @cindex file descriptor
133
134 Conventions generally follow those of scsh, @ref{The Scheme shell (scsh)}.
135
136 File ports are implemented using low-level operating system I/O
137 facilities, with optional buffering to improve efficiency; see
138 @ref{File Ports}.
139
140 Note that some procedures (e.g., @code{recv!}) will accept ports as
141 arguments, but will actually operate directly on the file descriptor
142 underlying the port. Any port buffering is ignored, including the
143 buffer which implements @code{peek-char} and @code{unread-char}.
144
145 The @code{force-output} and @code{drain-input} procedures can be used
146 to clear the buffers.
147
148 Each open file port has an associated operating system file descriptor.
149 File descriptors are generally not useful in Scheme programs; however
150 they may be needed when interfacing with foreign code and the Unix
151 environment.
152
153 A file descriptor can be extracted from a port and a new port can be
154 created from a file descriptor. However a file descriptor is just an
155 integer and the garbage collector doesn't recognize it as a reference
156 to the port. If all other references to the port were dropped, then
157 it's likely that the garbage collector would free the port, with the
158 side-effect of closing the file descriptor prematurely.
159
160 To assist the programmer in avoiding this problem, each port has an
161 associated @dfn{revealed count} which can be used to keep track of how many
162 times the underlying file descriptor has been stored in other places.
163 If a port's revealed count is greater than zero, the file descriptor
164 will not be closed when the port is garbage collected. A programmer
165 can therefore ensure that the revealed count will be greater than
166 zero if the file descriptor is needed elsewhere.
167
168 For the simple case where a file descriptor is ``imported'' once to become
169 a port, it does not matter if the file descriptor is closed when the
170 port is garbage collected. There is no need to maintain a revealed
171 count. Likewise when ``exporting'' a file descriptor to the external
172 environment, setting the revealed count is not required provided the
173 port is kept open (i.e., is pointed to by a live Scheme binding) while
174 the file descriptor is in use.
175
176 To correspond with traditional Unix behaviour, three file descriptors
177 (0, 1, and 2) are automatically imported when a program starts up and
178 assigned to the initial values of the current/standard input, output,
179 and error ports, respectively. The revealed count for each is
180 initially set to one, so that dropping references to one of these
181 ports will not result in its garbage collection: it could be retrieved
182 with @code{fdopen} or @code{fdes->ports}.
183
184 @deffn {Scheme Procedure} port-revealed port
185 @deffnx {C Function} scm_port_revealed (port)
186 Return the revealed count for @var{port}.
187 @end deffn
188
189 @deffn {Scheme Procedure} set-port-revealed! port rcount
190 @deffnx {C Function} scm_set_port_revealed_x (port, rcount)
191 Sets the revealed count for a @var{port} to @var{rcount}.
192 The return value is unspecified.
193 @end deffn
194
195 @deffn {Scheme Procedure} fileno port
196 @deffnx {C Function} scm_fileno (port)
197 Return the integer file descriptor underlying @var{port}. Does
198 not change its revealed count.
199 @end deffn
200
201 @deffn {Scheme Procedure} port->fdes port
202 Returns the integer file descriptor underlying @var{port}. As a
203 side effect the revealed count of @var{port} is incremented.
204 @end deffn
205
206 @deffn {Scheme Procedure} fdopen fdes modes
207 @deffnx {C Function} scm_fdopen (fdes, modes)
208 Return a new port based on the file descriptor @var{fdes}. Modes are
209 given by the string @var{modes}. The revealed count of the port is
210 initialized to zero. The @var{modes} string is the same as that
211 accepted by @code{open-file} (@pxref{File Ports, open-file}).
212 @end deffn
213
214 @deffn {Scheme Procedure} fdes->ports fdes
215 @deffnx {C Function} scm_fdes_to_ports (fdes)
216 Return a list of existing ports which have @var{fdes} as an
217 underlying file descriptor, without changing their revealed
218 counts.
219 @end deffn
220
221 @deffn {Scheme Procedure} fdes->inport fdes
222 Returns an existing input port which has @var{fdes} as its underlying file
223 descriptor, if one exists, and increments its revealed count.
224 Otherwise, returns a new input port with a revealed count of 1.
225 @end deffn
226
227 @deffn {Scheme Procedure} fdes->outport fdes
228 Returns an existing output port which has @var{fdes} as its underlying file
229 descriptor, if one exists, and increments its revealed count.
230 Otherwise, returns a new output port with a revealed count of 1.
231 @end deffn
232
233 @deffn {Scheme Procedure} primitive-move->fdes port fdes
234 @deffnx {C Function} scm_primitive_move_to_fdes (port, fdes)
235 Moves the underlying file descriptor for @var{port} to the integer
236 value @var{fdes} without changing the revealed count of @var{port}.
237 Any other ports already using this descriptor will be automatically
238 shifted to new descriptors and their revealed counts reset to zero.
239 The return value is @code{#f} if the file descriptor already had the
240 required value or @code{#t} if it was moved.
241 @end deffn
242
243 @deffn {Scheme Procedure} move->fdes port fdes
244 Moves the underlying file descriptor for @var{port} to the integer
245 value @var{fdes} and sets its revealed count to one. Any other ports
246 already using this descriptor will be automatically
247 shifted to new descriptors and their revealed counts reset to zero.
248 The return value is unspecified.
249 @end deffn
250
251 @deffn {Scheme Procedure} release-port-handle port
252 Decrements the revealed count for a port.
253 @end deffn
254
255 @deffn {Scheme Procedure} fsync port_or_fd
256 @deffnx {C Function} scm_fsync (port_or_fd)
257 Copies any unwritten data for the specified output file descriptor to disk.
258 If @var{port_or_fd} is a port, its buffer is flushed before the underlying
259 file descriptor is fsync'd.
260 The return value is unspecified.
261 @end deffn
262
263 @deffn {Scheme Procedure} open path flags [mode]
264 @deffnx {C Function} scm_open (path, flags, mode)
265 Open the file named by @var{path} for reading and/or writing.
266 @var{flags} is an integer specifying how the file should be opened.
267 @var{mode} is an integer specifying the permission bits of the file,
268 if it needs to be created, before the umask (@pxref{Processes}) is
269 applied. The default is 666 (Unix itself has no default).
270
271 @var{flags} can be constructed by combining variables using @code{logior}.
272 Basic flags are:
273
274 @defvar O_RDONLY
275 Open the file read-only.
276 @end defvar
277 @defvar O_WRONLY
278 Open the file write-only.
279 @end defvar
280 @defvar O_RDWR
281 Open the file read/write.
282 @end defvar
283 @defvar O_APPEND
284 Append to the file instead of truncating.
285 @end defvar
286 @defvar O_CREAT
287 Create the file if it does not already exist.
288 @end defvar
289
290 @xref{File Status Flags,,,libc,The GNU C Library Reference Manual},
291 for additional flags.
292 @end deffn
293
294 @deffn {Scheme Procedure} open-fdes path flags [mode]
295 @deffnx {C Function} scm_open_fdes (path, flags, mode)
296 Similar to @code{open} but return a file descriptor instead of
297 a port.
298 @end deffn
299
300 @deffn {Scheme Procedure} close fd_or_port
301 @deffnx {C Function} scm_close (fd_or_port)
302 Similar to @code{close-port} (@pxref{Closing, close-port}),
303 but also works on file descriptors. A side
304 effect of closing a file descriptor is that any ports using that file
305 descriptor are moved to a different file descriptor and have
306 their revealed counts set to zero.
307 @end deffn
308
309 @deffn {Scheme Procedure} close-fdes fd
310 @deffnx {C Function} scm_close_fdes (fd)
311 A simple wrapper for the @code{close} system call. Close file
312 descriptor @var{fd}, which must be an integer. Unlike @code{close},
313 the file descriptor will be closed even if a port is using it. The
314 return value is unspecified.
315 @end deffn
316
317 @deffn {Scheme Procedure} unread-char char [port]
318 @deffnx {C Function} scm_unread_char (char, port)
319 Place @var{char} in @var{port} so that it will be read by the next
320 read operation on that port. If called multiple times, the unread
321 characters will be read again in ``last-in, first-out'' order (i.e.@:
322 a stack). If @var{port} is not supplied, the current input port is
323 used.
324 @end deffn
325
326 @deffn {Scheme Procedure} unread-string str port
327 Place the string @var{str} in @var{port} so that its characters will be
328 read in subsequent read operations. If called multiple times, the
329 unread characters will be read again in last-in first-out order. If
330 @var{port} is not supplied, the current-input-port is used.
331 @end deffn
332
333 @deffn {Scheme Procedure} pipe
334 @deffnx {C Function} scm_pipe ()
335 @cindex pipe
336 Return a newly created pipe: a pair of ports which are linked
337 together on the local machine. The @acronym{CAR} is the input
338 port and the @acronym{CDR} is the output port. Data written (and
339 flushed) to the output port can be read from the input port.
340 Pipes are commonly used for communication with a newly forked
341 child process. The need to flush the output port can be
342 avoided by making it unbuffered using @code{setvbuf}.
343
344 @defvar PIPE_BUF
345 A write of up to @code{PIPE_BUF} many bytes to a pipe is atomic,
346 meaning when done it goes into the pipe instantaneously and as a
347 contiguous block (@pxref{Pipe Atomicity,, Atomicity of Pipe I/O, libc,
348 The GNU C Library Reference Manual}).
349 @end defvar
350
351 Note that the output port is likely to block if too much data has been
352 written but not yet read from the input port. Typically the capacity
353 is @code{PIPE_BUF} bytes.
354 @end deffn
355
356 The next group of procedures perform a @code{dup2}
357 system call, if @var{newfd} (an
358 integer) is supplied, otherwise a @code{dup}. The file descriptor to be
359 duplicated can be supplied as an integer or contained in a port. The
360 type of value returned varies depending on which procedure is used.
361
362 All procedures also have the side effect when performing @code{dup2} that any
363 ports using @var{newfd} are moved to a different file descriptor and have
364 their revealed counts set to zero.
365
366 @deffn {Scheme Procedure} dup->fdes fd_or_port [fd]
367 @deffnx {C Function} scm_dup_to_fdes (fd_or_port, fd)
368 Return a new integer file descriptor referring to the open file
369 designated by @var{fd_or_port}, which must be either an open
370 file port or a file descriptor.
371 @end deffn
372
373 @deffn {Scheme Procedure} dup->inport port/fd [newfd]
374 Returns a new input port using the new file descriptor.
375 @end deffn
376
377 @deffn {Scheme Procedure} dup->outport port/fd [newfd]
378 Returns a new output port using the new file descriptor.
379 @end deffn
380
381 @deffn {Scheme Procedure} dup port/fd [newfd]
382 Returns a new port if @var{port/fd} is a port, with the same mode as the
383 supplied port, otherwise returns an integer file descriptor.
384 @end deffn
385
386 @deffn {Scheme Procedure} dup->port port/fd mode [newfd]
387 Returns a new port using the new file descriptor. @var{mode} supplies a
388 mode string for the port (@pxref{File Ports, open-file}).
389 @end deffn
390
391 @deffn {Scheme Procedure} duplicate-port port modes
392 Returns a new port which is opened on a duplicate of the file
393 descriptor underlying @var{port}, with mode string @var{modes}
394 as for @ref{File Ports, open-file}. The two ports
395 will share a file position and file status flags.
396
397 Unexpected behaviour can result if both ports are subsequently used
398 and the original and/or duplicate ports are buffered.
399 The mode string can include @code{0} to obtain an unbuffered duplicate
400 port.
401
402 This procedure is equivalent to @code{(dup->port @var{port} @var{modes})}.
403 @end deffn
404
405 @deffn {Scheme Procedure} redirect-port old_port new_port
406 @deffnx {C Function} scm_redirect_port (old_port, new_port)
407 This procedure takes two ports and duplicates the underlying file
408 descriptor from @var{old_port} into @var{new_port}. The
409 current file descriptor in @var{new_port} will be closed.
410 After the redirection the two ports will share a file position
411 and file status flags.
412
413 The return value is unspecified.
414
415 Unexpected behaviour can result if both ports are subsequently used
416 and the original and/or duplicate ports are buffered.
417
418 This procedure does not have any side effects on other ports or
419 revealed counts.
420 @end deffn
421
422 @deffn {Scheme Procedure} dup2 oldfd newfd
423 @deffnx {C Function} scm_dup2 (oldfd, newfd)
424 A simple wrapper for the @code{dup2} system call.
425 Copies the file descriptor @var{oldfd} to descriptor
426 number @var{newfd}, replacing the previous meaning
427 of @var{newfd}. Both @var{oldfd} and @var{newfd} must
428 be integers.
429 Unlike for @code{dup->fdes} or @code{primitive-move->fdes}, no attempt
430 is made to move away ports which are using @var{newfd}.
431 The return value is unspecified.
432 @end deffn
433
434 @deffn {Scheme Procedure} port-mode port
435 Return the port modes associated with the open port @var{port}.
436 These will not necessarily be identical to the modes used when
437 the port was opened, since modes such as ``append'' which are
438 used only during port creation are not retained.
439 @end deffn
440
441 @deffn {Scheme Procedure} port-for-each proc
442 @deffnx {C Function} scm_port_for_each (SCM proc)
443 @deffnx {C Function} scm_c_port_for_each (void (*proc)(void *, SCM), void *data)
444 Apply @var{proc} to each port in the Guile port table
445 (FIXME: what is the Guile port table?)
446 in turn. The return value is unspecified. More specifically,
447 @var{proc} is applied exactly once to every port that exists in the
448 system at the time @code{port-for-each} is invoked. Changes to the
449 port table while @code{port-for-each} is running have no effect as far
450 as @code{port-for-each} is concerned.
451
452 The C function @code{scm_port_for_each} takes a Scheme procedure
453 encoded as a @code{SCM} value, while @code{scm_c_port_for_each} takes
454 a pointer to a C function and passes along a arbitrary @var{data}
455 cookie.
456 @end deffn
457
458 @deffn {Scheme Procedure} setvbuf port mode [size]
459 @deffnx {C Function} scm_setvbuf (port, mode, size)
460 @cindex port buffering
461 Set the buffering mode for @var{port}. @var{mode} can be:
462
463 @defvar _IONBF
464 non-buffered
465 @end defvar
466 @defvar _IOLBF
467 line buffered
468 @end defvar
469 @defvar _IOFBF
470 block buffered, using a newly allocated buffer of @var{size} bytes.
471 If @var{size} is omitted, a default size will be used.
472 @end defvar
473 @end deffn
474
475 @deffn {Scheme Procedure} fcntl port/fd cmd [value]
476 @deffnx {C Function} scm_fcntl (object, cmd, value)
477 Apply @var{cmd} on @var{port/fd}, either a port or file descriptor.
478 The @var{value} argument is used by the @code{SET} commands described
479 below, it's an integer value.
480
481 Values for @var{cmd} are:
482
483 @defvar F_DUPFD
484 Duplicate the file descriptor, the same as @code{dup->fdes} above
485 does.
486 @end defvar
487
488 @defvar F_GETFD
489 @defvarx F_SETFD
490 Get or set flags associated with the file descriptor. The only flag
491 is the following,
492
493 @defvar FD_CLOEXEC
494 ``Close on exec'', meaning the file descriptor will be closed on an
495 @code{exec} call (a successful such call). For example to set that
496 flag,
497
498 @example
499 (fcntl port F_SETFD FD_CLOEXEC)
500 @end example
501
502 Or better, set it but leave any other possible future flags unchanged,
503
504 @example
505 (fcntl port F_SETFD (logior FD_CLOEXEC
506 (fcntl port F_GETFD)))
507 @end example
508 @end defvar
509 @end defvar
510
511 @defvar F_GETFL
512 @defvarx F_SETFL
513 Get or set flags associated with the open file. These flags are
514 @code{O_RDONLY} etc described under @code{open} above.
515
516 A common use is to set @code{O_NONBLOCK} on a network socket. The
517 following sets that flag, and leaves other flags unchanged.
518
519 @example
520 (fcntl sock F_SETFL (logior O_NONBLOCK
521 (fcntl sock F_GETFL)))
522 @end example
523 @end defvar
524
525 @defvar F_GETOWN
526 @defvarx F_SETOWN
527 Get or set the process ID of a socket's owner, for @code{SIGIO} signals.
528 @end defvar
529 @end deffn
530
531 @deffn {Scheme Procedure} flock file operation
532 @deffnx {C Function} scm_flock (file, operation)
533 @cindex file locking
534 Apply or remove an advisory lock on an open file.
535 @var{operation} specifies the action to be done:
536
537 @defvar LOCK_SH
538 Shared lock. More than one process may hold a shared lock
539 for a given file at a given time.
540 @end defvar
541 @defvar LOCK_EX
542 Exclusive lock. Only one process may hold an exclusive lock
543 for a given file at a given time.
544 @end defvar
545 @defvar LOCK_UN
546 Unlock the file.
547 @end defvar
548 @defvar LOCK_NB
549 Don't block when locking. This is combined with one of the other
550 operations using @code{logior} (@pxref{Bitwise Operations}). If
551 @code{flock} would block an @code{EWOULDBLOCK} error is thrown
552 (@pxref{Conventions}).
553 @end defvar
554
555 The return value is not specified. @var{file} may be an open
556 file descriptor or an open file descriptor port.
557
558 Note that @code{flock} does not lock files across NFS.
559 @end deffn
560
561 @deffn {Scheme Procedure} select reads writes excepts [secs [usecs]]
562 @deffnx {C Function} scm_select (reads, writes, excepts, secs, usecs)
563 This procedure has a variety of uses: waiting for the ability
564 to provide input, accept output, or the existence of
565 exceptional conditions on a collection of ports or file
566 descriptors, or waiting for a timeout to occur.
567 It also returns if interrupted by a signal.
568
569 @var{reads}, @var{writes} and @var{excepts} can be lists or
570 vectors, with each member a port or a file descriptor.
571 The value returned is a list of three corresponding
572 lists or vectors containing only the members which meet the
573 specified requirement. The ability of port buffers to
574 provide input or accept output is taken into account.
575 Ordering of the input lists or vectors is not preserved.
576
577 The optional arguments @var{secs} and @var{usecs} specify the
578 timeout. Either @var{secs} can be specified alone, as
579 either an integer or a real number, or both @var{secs} and
580 @var{usecs} can be specified as integers, in which case
581 @var{usecs} is an additional timeout expressed in
582 microseconds. If @var{secs} is omitted or is @code{#f} then
583 select will wait for as long as it takes for one of the other
584 conditions to be satisfied.
585
586 The scsh version of @code{select} differs as follows:
587 Only vectors are accepted for the first three arguments.
588 The @var{usecs} argument is not supported.
589 Multiple values are returned instead of a list.
590 Duplicates in the input vectors appear only once in output.
591 An additional @code{select!} interface is provided.
592 @end deffn
593
594 @node File System
595 @subsection File System
596 @cindex file system
597
598 These procedures allow querying and setting file system attributes
599 (such as owner,
600 permissions, sizes and types of files); deleting, copying, renaming and
601 linking files; creating and removing directories and querying their
602 contents; syncing the file system and creating special files.
603
604 @deffn {Scheme Procedure} access? path how
605 @deffnx {C Function} scm_access (path, how)
606 Test accessibility of a file under the real UID and GID of the calling
607 process. The return is @code{#t} if @var{path} exists and the
608 permissions requested by @var{how} are all allowed, or @code{#f} if
609 not.
610
611 @var{how} is an integer which is one of the following values, or a
612 bitwise-OR (@code{logior}) of multiple values.
613
614 @defvar R_OK
615 Test for read permission.
616 @end defvar
617 @defvar W_OK
618 Test for write permission.
619 @end defvar
620 @defvar X_OK
621 Test for execute permission.
622 @end defvar
623 @defvar F_OK
624 Test for existence of the file. This is implied by each of the other
625 tests, so there's no need to combine it with them.
626 @end defvar
627
628 It's important to note that @code{access?} does not simply indicate
629 what will happen on attempting to read or write a file. In normal
630 circumstances it does, but in a set-UID or set-GID program it doesn't
631 because @code{access?} tests the real ID, whereas an open or execute
632 attempt uses the effective ID.
633
634 A program which will never run set-UID/GID can ignore the difference
635 between real and effective IDs, but for maximum generality, especially
636 in library functions, it's best not to use @code{access?} to predict
637 the result of an open or execute, instead simply attempt that and
638 catch any exception.
639
640 The main use for @code{access?} is to let a set-UID/GID program
641 determine what the invoking user would have been allowed to do,
642 without the greater (or perhaps lesser) privileges afforded by the
643 effective ID. For more on this, see @ref{Testing File Access,,, libc,
644 The GNU C Library Reference Manual}.
645 @end deffn
646
647 @findex fstat
648 @deffn {Scheme Procedure} stat object
649 @deffnx {C Function} scm_stat (object)
650 Return an object containing various information about the file
651 determined by @var{object}. @var{object} can be a string containing
652 a file name or a port or integer file descriptor which is open
653 on a file (in which case @code{fstat} is used as the underlying
654 system call).
655
656 The object returned by @code{stat} can be passed as a single
657 parameter to the following procedures, all of which return
658 integers:
659
660 @deffn {Scheme Procedure} stat:dev st
661 The device number containing the file.
662 @end deffn
663 @deffn {Scheme Procedure} stat:ino st
664 The file serial number, which distinguishes this file from all
665 other files on the same device.
666 @end deffn
667 @deffn {Scheme Procedure} stat:mode st
668 The mode of the file. This is an integer which incorporates file type
669 information and file permission bits. See also @code{stat:type} and
670 @code{stat:perms} below.
671 @end deffn
672 @deffn {Scheme Procedure} stat:nlink st
673 The number of hard links to the file.
674 @end deffn
675 @deffn {Scheme Procedure} stat:uid st
676 The user ID of the file's owner.
677 @end deffn
678 @deffn {Scheme Procedure} stat:gid st
679 The group ID of the file.
680 @end deffn
681 @deffn {Scheme Procedure} stat:rdev st
682 Device ID; this entry is defined only for character or block special
683 files. On some systems this field is not available at all, in which
684 case @code{stat:rdev} returns @code{#f}.
685 @end deffn
686 @deffn {Scheme Procedure} stat:size st
687 The size of a regular file in bytes.
688 @end deffn
689 @deffn {Scheme Procedure} stat:atime st
690 The last access time for the file, in seconds.
691 @end deffn
692 @deffn {Scheme Procedure} stat:mtime st
693 The last modification time for the file, in seconds.
694 @end deffn
695 @deffn {Scheme Procedure} stat:ctime st
696 The last modification time for the attributes of the file, in seconds.
697 @end deffn
698 @deffn {Scheme Procedure} stat:atimensec st
699 @deffnx {Scheme Procedure} stat:mtimensec st
700 @deffnx {Scheme Procedure} stat:ctimensec st
701 The fractional part of a file's access, modification, or attribute modification
702 time, in nanoseconds. Nanosecond timestamps are only available on some operating
703 systems and file systems. If Guile cannot retrieve nanosecond-level timestamps
704 for a file, these fields will be set to 0.
705 @end deffn
706 @deffn {Scheme Procedure} stat:blksize st
707 The optimal block size for reading or writing the file, in bytes. On
708 some systems this field is not available, in which case
709 @code{stat:blksize} returns a sensible suggested block size.
710 @end deffn
711 @deffn {Scheme Procedure} stat:blocks st
712 The amount of disk space that the file occupies measured in units of
713 512 byte blocks. On some systems this field is not available, in
714 which case @code{stat:blocks} returns @code{#f}.
715 @end deffn
716
717 In addition, the following procedures return the information
718 from @code{stat:mode} in a more convenient form:
719
720 @deffn {Scheme Procedure} stat:type st
721 A symbol representing the type of file. Possible values are
722 @samp{regular}, @samp{directory}, @samp{symlink},
723 @samp{block-special}, @samp{char-special}, @samp{fifo}, @samp{socket},
724 and @samp{unknown}.
725 @end deffn
726 @deffn {Scheme Procedure} stat:perms st
727 An integer representing the access permission bits.
728 @end deffn
729 @end deffn
730
731 @deffn {Scheme Procedure} lstat path
732 @deffnx {C Function} scm_lstat (path)
733 Similar to @code{stat}, but does not follow symbolic links, i.e.,
734 it will return information about a symbolic link itself, not the
735 file it points to. @var{path} must be a string.
736 @end deffn
737
738 @deffn {Scheme Procedure} readlink path
739 @deffnx {C Function} scm_readlink (path)
740 Return the value of the symbolic link named by @var{path} (a
741 string), i.e., the file that the link points to.
742 @end deffn
743
744 @findex fchown
745 @findex lchown
746 @deffn {Scheme Procedure} chown object owner group
747 @deffnx {C Function} scm_chown (object, owner, group)
748 Change the ownership and group of the file referred to by @var{object}
749 to the integer values @var{owner} and @var{group}. @var{object} can
750 be a string containing a file name or, if the platform supports
751 @code{fchown} (@pxref{File Owner,,,libc,The GNU C Library Reference
752 Manual}), a port or integer file descriptor which is open on the file.
753 The return value is unspecified.
754
755 If @var{object} is a symbolic link, either the
756 ownership of the link or the ownership of the referenced file will be
757 changed depending on the operating system (lchown is
758 unsupported at present). If @var{owner} or @var{group} is specified
759 as @code{-1}, then that ID is not changed.
760 @end deffn
761
762 @findex fchmod
763 @deffn {Scheme Procedure} chmod object mode
764 @deffnx {C Function} scm_chmod (object, mode)
765 Changes the permissions of the file referred to by @var{object}.
766 @var{object} can be a string containing a file name or a port or integer file
767 descriptor which is open on a file (in which case @code{fchmod} is used
768 as the underlying system call).
769 @var{mode} specifies
770 the new permissions as a decimal number, e.g., @code{(chmod "foo" #o755)}.
771 The return value is unspecified.
772 @end deffn
773
774 @deffn {Scheme Procedure} utime pathname [actime [modtime [actimens [modtimens [flags]]]]]
775 @deffnx {C Function} scm_utime (pathname, actime, modtime, actimens, modtimens, flags)
776 @code{utime} sets the access and modification times for the
777 file named by @var{pathname}. If @var{actime} or @var{modtime} is
778 not supplied, then the current time is used. @var{actime} and
779 @var{modtime} must be integer time values as returned by the
780 @code{current-time} procedure.
781
782 The optional @var{actimens} and @var{modtimens} are nanoseconds
783 to add @var{actime} and @var{modtime}. Nanosecond precision is
784 only supported on some combinations of file systems and operating
785 systems.
786 @lisp
787 (utime "foo" (- (current-time) 3600))
788 @end lisp
789 will set the access time to one hour in the past and the
790 modification time to the current time.
791 @end deffn
792
793 @findex unlink
794 @deffn {Scheme Procedure} delete-file str
795 @deffnx {C Function} scm_delete_file (str)
796 Deletes (or ``unlinks'') the file whose path is specified by
797 @var{str}.
798 @end deffn
799
800 @deffn {Scheme Procedure} copy-file oldfile newfile
801 @deffnx {C Function} scm_copy_file (oldfile, newfile)
802 Copy the file specified by @var{oldfile} to @var{newfile}.
803 The return value is unspecified.
804 @end deffn
805
806 @deffn {Scheme Procedure} sendfile out in count [offset]
807 @deffnx {C Function} scm_sendfile (out, in, count, offset)
808 Send @var{count} bytes from @var{in} to @var{out}, both of which
809 are either open file ports or file descriptors. When
810 @var{offset} is omitted, start reading from @var{in}'s current
811 position; otherwise, start reading at @var{offset}.
812
813 When @var{in} is a port, it is often preferable to specify @var{offset},
814 because @var{in}'s offset as a port may be different from the offset of
815 its underlying file descriptor.
816
817 On systems that support it, such as GNU/Linux, this procedure uses the
818 @code{sendfile} libc function, which usually corresponds to a system
819 call. This is faster than doing a series of @code{read} and
820 @code{write} system calls. A typical application is to send a file over
821 a socket.
822
823 In some cases, the @code{sendfile} libc function may return
824 @code{EINVAL} or @code{ENOSYS}. In that case, Guile's @code{sendfile}
825 procedure automatically falls back to doing a series of @code{read} and
826 @code{write} calls.
827 @end deffn
828
829 @findex rename
830 @deffn {Scheme Procedure} rename-file oldname newname
831 @deffnx {C Function} scm_rename (oldname, newname)
832 Renames the file specified by @var{oldname} to @var{newname}.
833 The return value is unspecified.
834 @end deffn
835
836 @deffn {Scheme Procedure} link oldpath newpath
837 @deffnx {C Function} scm_link (oldpath, newpath)
838 Creates a new name @var{newpath} in the file system for the
839 file named by @var{oldpath}. If @var{oldpath} is a symbolic
840 link, the link may or may not be followed depending on the
841 system.
842 @end deffn
843
844 @deffn {Scheme Procedure} symlink oldpath newpath
845 @deffnx {C Function} scm_symlink (oldpath, newpath)
846 Create a symbolic link named @var{newpath} with the value (i.e., pointing to)
847 @var{oldpath}. The return value is unspecified.
848 @end deffn
849
850 @deffn {Scheme Procedure} mkdir path [mode]
851 @deffnx {C Function} scm_mkdir (path, mode)
852 Create a new directory named by @var{path}. If @var{mode} is omitted
853 then the permissions of the directory file are set using the current
854 umask (@pxref{Processes}). Otherwise they are set to the decimal
855 value specified with @var{mode}. The return value is unspecified.
856 @end deffn
857
858 @deffn {Scheme Procedure} rmdir path
859 @deffnx {C Function} scm_rmdir (path)
860 Remove the existing directory named by @var{path}. The directory must
861 be empty for this to succeed. The return value is unspecified.
862 @end deffn
863
864 @deffn {Scheme Procedure} opendir dirname
865 @deffnx {C Function} scm_opendir (dirname)
866 @cindex directory contents
867 Open the directory specified by @var{dirname} and return a directory
868 stream.
869
870 Before using this and the procedures below, make sure to see the
871 higher-level procedures for directory traversal that are available
872 (@pxref{File Tree Walk}).
873 @end deffn
874
875 @deffn {Scheme Procedure} directory-stream? object
876 @deffnx {C Function} scm_directory_stream_p (object)
877 Return a boolean indicating whether @var{object} is a directory
878 stream as returned by @code{opendir}.
879 @end deffn
880
881 @deffn {Scheme Procedure} readdir stream
882 @deffnx {C Function} scm_readdir (stream)
883 Return (as a string) the next directory entry from the directory stream
884 @var{stream}. If there is no remaining entry to be read then the
885 end of file object is returned.
886 @end deffn
887
888 @deffn {Scheme Procedure} rewinddir stream
889 @deffnx {C Function} scm_rewinddir (stream)
890 Reset the directory port @var{stream} so that the next call to
891 @code{readdir} will return the first directory entry.
892 @end deffn
893
894 @deffn {Scheme Procedure} closedir stream
895 @deffnx {C Function} scm_closedir (stream)
896 Close the directory stream @var{stream}.
897 The return value is unspecified.
898 @end deffn
899
900 Here is an example showing how to display all the entries in a
901 directory:
902
903 @lisp
904 (define dir (opendir "/usr/lib"))
905 (do ((entry (readdir dir) (readdir dir)))
906 ((eof-object? entry))
907 (display entry)(newline))
908 (closedir dir)
909 @end lisp
910
911 @deffn {Scheme Procedure} sync
912 @deffnx {C Function} scm_sync ()
913 Flush the operating system disk buffers.
914 The return value is unspecified.
915 @end deffn
916
917 @deffn {Scheme Procedure} mknod path type perms dev
918 @deffnx {C Function} scm_mknod (path, type, perms, dev)
919 @cindex device file
920 Creates a new special file, such as a file corresponding to a device.
921 @var{path} specifies the name of the file. @var{type} should be one
922 of the following symbols: @samp{regular}, @samp{directory},
923 @samp{symlink}, @samp{block-special}, @samp{char-special},
924 @samp{fifo}, or @samp{socket}. @var{perms} (an integer) specifies the
925 file permissions. @var{dev} (an integer) specifies which device the
926 special file refers to. Its exact interpretation depends on the kind
927 of special file being created.
928
929 E.g.,
930 @lisp
931 (mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))
932 @end lisp
933
934 The return value is unspecified.
935 @end deffn
936
937 @deffn {Scheme Procedure} tmpnam
938 @deffnx {C Function} scm_tmpnam ()
939 @cindex temporary file
940 Return an auto-generated name of a temporary file, a file which
941 doesn't already exist. The name includes a path, it's usually in
942 @file{/tmp} but that's system dependent.
943
944 Care must be taken when using @code{tmpnam}. In between choosing the
945 name and creating the file another program might use that name, or an
946 attacker might even make it a symlink pointing at something important
947 and causing you to overwrite that.
948
949 The safe way is to create the file using @code{open} with
950 @code{O_EXCL} to avoid any overwriting. A loop can try again with
951 another name if the file exists (error @code{EEXIST}).
952 @code{mkstemp!} below does that.
953 @end deffn
954
955 @deffn {Scheme Procedure} mkstemp! tmpl
956 @deffnx {C Function} scm_mkstemp (tmpl)
957 @cindex temporary file
958 Create a new unique file in the file system and return a new buffered
959 port open for reading and writing to the file.
960
961 @var{tmpl} is a string specifying where the file should be created: it
962 must end with @samp{XXXXXX} and those @samp{X}s will be changed in the
963 string to return the name of the file. (@code{port-filename} on the
964 port also gives the name.)
965
966 POSIX doesn't specify the permissions mode of the file, on GNU and
967 most systems it's @code{#o600}. An application can use @code{chmod}
968 to relax that if desired. For example @code{#o666} less @code{umask},
969 which is usual for ordinary file creation,
970
971 @example
972 (let ((port (mkstemp! (string-copy "/tmp/myfile-XXXXXX"))))
973 (chmod port (logand #o666 (lognot (umask))))
974 ...)
975 @end example
976 @end deffn
977
978 @deffn {Scheme Procedure} tmpfile
979 @deffnx {C Function} scm_tmpfile ()
980 Return an input/output port to a unique temporary file
981 named using the path prefix @code{P_tmpdir} defined in
982 @file{stdio.h}.
983 The file is automatically deleted when the port is closed
984 or the program terminates.
985 @end deffn
986
987 @deffn {Scheme Procedure} dirname filename
988 @deffnx {C Function} scm_dirname (filename)
989 Return the directory name component of the file name
990 @var{filename}. If @var{filename} does not contain a directory
991 component, @code{.} is returned.
992 @end deffn
993
994 @deffn {Scheme Procedure} basename filename [suffix]
995 @deffnx {C Function} scm_basename (filename, suffix)
996 Return the base name of the file name @var{filename}. The
997 base name is the file name without any directory components.
998 If @var{suffix} is provided, and is equal to the end of
999 @var{basename}, it is removed also.
1000
1001 @lisp
1002 (basename "/tmp/test.xml" ".xml")
1003 @result{} "test"
1004 @end lisp
1005 @end deffn
1006
1007 @deffn {Scheme Procedure} file-exists? filename
1008 Return @code{#t} if the file named @var{filename} exists, @code{#f} if
1009 not.
1010 @end deffn
1011
1012 @cindex file name separator
1013 @cindex absolute file name
1014
1015 Many operating systems, such as GNU, use @code{/} (forward slash) to
1016 separate the components of a file name; any file name starting with
1017 @code{/} is considered an @dfn{absolute file name}. These conventions
1018 are specified by the POSIX Base Definitions, which refer to conforming
1019 file names as ``pathnames''. Some operating systems use a different
1020 convention; in particular, Windows uses @code{\} (backslash) as the file
1021 name separator, and also has the notion of @dfn{volume names} like
1022 @code{C:\} for absolute file names. The following procedures and
1023 variables provide support for portable file name manipulations.
1024
1025 @deffn {Scheme Procedure} system-file-name-convention
1026 Return either @code{posix} or @code{windows}, depending on
1027 what kind of system this Guile is running on.
1028 @end deffn
1029
1030 @deffn {Scheme Procedure} file-name-separator? c
1031 Return true if character @var{c} is a file name separator on the host
1032 platform.
1033 @end deffn
1034
1035 @deffn {Scheme Procedure} absolute-file-name? file-name
1036 Return true if @var{file-name} denotes an absolute file name on the host
1037 platform.
1038 @end deffn
1039
1040 @defvr {Scheme Variable} file-name-separator-string
1041 The preferred file name separator.
1042
1043 Note that on MinGW builds for Windows, both @code{/} and @code{\} are
1044 valid separators. Thus, programs should not assume that
1045 @code{file-name-separator-string} is the @emph{only} file name
1046 separator---e.g., when extracting the components of a file name.
1047 @end defvr
1048
1049
1050 @node User Information
1051 @subsection User Information
1052 @cindex user information
1053 @cindex password file
1054 @cindex group file
1055
1056 The facilities in this section provide an interface to the user and
1057 group database.
1058 They should be used with care since they are not reentrant.
1059
1060 The following functions accept an object representing user information
1061 and return a selected component:
1062
1063 @deffn {Scheme Procedure} passwd:name pw
1064 The name of the userid.
1065 @end deffn
1066 @deffn {Scheme Procedure} passwd:passwd pw
1067 The encrypted passwd.
1068 @end deffn
1069 @deffn {Scheme Procedure} passwd:uid pw
1070 The user id number.
1071 @end deffn
1072 @deffn {Scheme Procedure} passwd:gid pw
1073 The group id number.
1074 @end deffn
1075 @deffn {Scheme Procedure} passwd:gecos pw
1076 The full name.
1077 @end deffn
1078 @deffn {Scheme Procedure} passwd:dir pw
1079 The home directory.
1080 @end deffn
1081 @deffn {Scheme Procedure} passwd:shell pw
1082 The login shell.
1083 @end deffn
1084 @sp 1
1085
1086 @deffn {Scheme Procedure} getpwuid uid
1087 Look up an integer userid in the user database.
1088 @end deffn
1089
1090 @deffn {Scheme Procedure} getpwnam name
1091 Look up a user name string in the user database.
1092 @end deffn
1093
1094 @deffn {Scheme Procedure} setpwent
1095 Initializes a stream used by @code{getpwent} to read from the user database.
1096 The next use of @code{getpwent} will return the first entry. The
1097 return value is unspecified.
1098 @end deffn
1099
1100 @deffn {Scheme Procedure} getpwent
1101 Read the next entry in the user database stream. The return is a
1102 passwd user object as above, or @code{#f} when no more entries.
1103 @end deffn
1104
1105 @deffn {Scheme Procedure} endpwent
1106 Closes the stream used by @code{getpwent}. The return value is unspecified.
1107 @end deffn
1108
1109 @deffn {Scheme Procedure} setpw [arg]
1110 @deffnx {C Function} scm_setpwent (arg)
1111 If called with a true argument, initialize or reset the password data
1112 stream. Otherwise, close the stream. The @code{setpwent} and
1113 @code{endpwent} procedures are implemented on top of this.
1114 @end deffn
1115
1116 @deffn {Scheme Procedure} getpw [user]
1117 @deffnx {C Function} scm_getpwuid (user)
1118 Look up an entry in the user database. @var{user} can be an integer,
1119 a string, or omitted, giving the behaviour of getpwuid, getpwnam
1120 or getpwent respectively.
1121 @end deffn
1122
1123 The following functions accept an object representing group information
1124 and return a selected component:
1125
1126 @deffn {Scheme Procedure} group:name gr
1127 The group name.
1128 @end deffn
1129 @deffn {Scheme Procedure} group:passwd gr
1130 The encrypted group password.
1131 @end deffn
1132 @deffn {Scheme Procedure} group:gid gr
1133 The group id number.
1134 @end deffn
1135 @deffn {Scheme Procedure} group:mem gr
1136 A list of userids which have this group as a supplementary group.
1137 @end deffn
1138 @sp 1
1139
1140 @deffn {Scheme Procedure} getgrgid gid
1141 Look up an integer group id in the group database.
1142 @end deffn
1143
1144 @deffn {Scheme Procedure} getgrnam name
1145 Look up a group name in the group database.
1146 @end deffn
1147
1148 @deffn {Scheme Procedure} setgrent
1149 Initializes a stream used by @code{getgrent} to read from the group database.
1150 The next use of @code{getgrent} will return the first entry.
1151 The return value is unspecified.
1152 @end deffn
1153
1154 @deffn {Scheme Procedure} getgrent
1155 Return the next entry in the group database, using the stream set by
1156 @code{setgrent}.
1157 @end deffn
1158
1159 @deffn {Scheme Procedure} endgrent
1160 Closes the stream used by @code{getgrent}.
1161 The return value is unspecified.
1162 @end deffn
1163
1164 @deffn {Scheme Procedure} setgr [arg]
1165 @deffnx {C Function} scm_setgrent (arg)
1166 If called with a true argument, initialize or reset the group data
1167 stream. Otherwise, close the stream. The @code{setgrent} and
1168 @code{endgrent} procedures are implemented on top of this.
1169 @end deffn
1170
1171 @deffn {Scheme Procedure} getgr [group]
1172 @deffnx {C Function} scm_getgrgid (group)
1173 Look up an entry in the group database. @var{group} can be an integer,
1174 a string, or omitted, giving the behaviour of getgrgid, getgrnam
1175 or getgrent respectively.
1176 @end deffn
1177
1178 In addition to the accessor procedures for the user database, the
1179 following shortcut procedure is also available.
1180
1181 @deffn {Scheme Procedure} getlogin
1182 @deffnx {C Function} scm_getlogin ()
1183 Return a string containing the name of the user logged in on
1184 the controlling terminal of the process, or @code{#f} if this
1185 information cannot be obtained.
1186 @end deffn
1187
1188
1189 @node Time
1190 @subsection Time
1191 @cindex time
1192
1193 @deffn {Scheme Procedure} current-time
1194 @deffnx {C Function} scm_current_time ()
1195 Return the number of seconds since 1970-01-01 00:00:00 @acronym{UTC},
1196 excluding leap seconds.
1197 @end deffn
1198
1199 @deffn {Scheme Procedure} gettimeofday
1200 @deffnx {C Function} scm_gettimeofday ()
1201 Return a pair containing the number of seconds and microseconds
1202 since 1970-01-01 00:00:00 @acronym{UTC}, excluding leap seconds. Note:
1203 whether true microsecond resolution is available depends on the
1204 operating system.
1205 @end deffn
1206
1207 The following procedures either accept an object representing a broken down
1208 time and return a selected component, or accept an object representing
1209 a broken down time and a value and set the component to the value.
1210 The numbers in parentheses give the usual range.
1211
1212 @deffn {Scheme Procedure} tm:sec tm
1213 @deffnx {Scheme Procedure} set-tm:sec tm val
1214 Seconds (0-59).
1215 @end deffn
1216 @deffn {Scheme Procedure} tm:min tm
1217 @deffnx {Scheme Procedure} set-tm:min tm val
1218 Minutes (0-59).
1219 @end deffn
1220 @deffn {Scheme Procedure} tm:hour tm
1221 @deffnx {Scheme Procedure} set-tm:hour tm val
1222 Hours (0-23).
1223 @end deffn
1224 @deffn {Scheme Procedure} tm:mday tm
1225 @deffnx {Scheme Procedure} set-tm:mday tm val
1226 Day of the month (1-31).
1227 @end deffn
1228 @deffn {Scheme Procedure} tm:mon tm
1229 @deffnx {Scheme Procedure} set-tm:mon tm val
1230 Month (0-11).
1231 @end deffn
1232 @deffn {Scheme Procedure} tm:year tm
1233 @deffnx {Scheme Procedure} set-tm:year tm val
1234 Year (70-), the year minus 1900.
1235 @end deffn
1236 @deffn {Scheme Procedure} tm:wday tm
1237 @deffnx {Scheme Procedure} set-tm:wday tm val
1238 Day of the week (0-6) with Sunday represented as 0.
1239 @end deffn
1240 @deffn {Scheme Procedure} tm:yday tm
1241 @deffnx {Scheme Procedure} set-tm:yday tm val
1242 Day of the year (0-364, 365 in leap years).
1243 @end deffn
1244 @deffn {Scheme Procedure} tm:isdst tm
1245 @deffnx {Scheme Procedure} set-tm:isdst tm val
1246 Daylight saving indicator (0 for ``no'', greater than 0 for ``yes'', less than
1247 0 for ``unknown'').
1248 @end deffn
1249 @deffn {Scheme Procedure} tm:gmtoff tm
1250 @deffnx {Scheme Procedure} set-tm:gmtoff tm val
1251 Time zone offset in seconds west of @acronym{UTC} (-46800 to 43200).
1252 For example on East coast USA (zone @samp{EST+5}) this would be 18000
1253 (ie.@: @m{5\times60\times60,5*60*60}) in winter, or 14400
1254 (ie.@: @m{4\times60\times60,4*60*60}) during daylight savings.
1255
1256 Note @code{tm:gmtoff} is not the same as @code{tm_gmtoff} in the C
1257 @code{tm} structure. @code{tm_gmtoff} is seconds east and hence the
1258 negative of the value here.
1259 @end deffn
1260 @deffn {Scheme Procedure} tm:zone tm
1261 @deffnx {Scheme Procedure} set-tm:zone tm val
1262 Time zone label (a string), not necessarily unique.
1263 @end deffn
1264 @sp 1
1265
1266 @deffn {Scheme Procedure} localtime time [zone]
1267 @deffnx {C Function} scm_localtime (time, zone)
1268 @cindex local time
1269 Return an object representing the broken down components of
1270 @var{time}, an integer like the one returned by
1271 @code{current-time}. The time zone for the calculation is
1272 optionally specified by @var{zone} (a string), otherwise the
1273 @env{TZ} environment variable or the system default is used.
1274 @end deffn
1275
1276 @deffn {Scheme Procedure} gmtime time
1277 @deffnx {C Function} scm_gmtime (time)
1278 Return an object representing the broken down components of
1279 @var{time}, an integer like the one returned by
1280 @code{current-time}. The values are calculated for @acronym{UTC}.
1281 @end deffn
1282
1283 @deffn {Scheme Procedure} mktime sbd-time [zone]
1284 @deffnx {C Function} scm_mktime (sbd_time, zone)
1285 For a broken down time object @var{sbd-time}, return a pair the
1286 @code{car} of which is an integer time like @code{current-time}, and
1287 the @code{cdr} of which is a new broken down time with normalized
1288 fields.
1289
1290 @var{zone} is a timezone string, or the default is the @env{TZ}
1291 environment variable or the system default (@pxref{TZ Variable,,
1292 Specifying the Time Zone with @env{TZ}, libc, GNU C Library Reference
1293 Manual}). @var{sbd-time} is taken to be in that @var{zone}.
1294
1295 The following fields of @var{sbd-time} are used: @code{tm:year},
1296 @code{tm:mon}, @code{tm:mday}, @code{tm:hour}, @code{tm:min},
1297 @code{tm:sec}, @code{tm:isdst}. The values can be outside their usual
1298 ranges. For example @code{tm:hour} normally goes up to 23, but a
1299 value say 33 would mean 9 the following day.
1300
1301 @code{tm:isdst} in @var{sbd-time} says whether the time given is with
1302 daylight savings or not. This is ignored if @var{zone} doesn't have
1303 any daylight savings adjustment amount.
1304
1305 The broken down time in the return normalizes the values of
1306 @var{sbd-time} by bringing them into their usual ranges, and using the
1307 actual daylight savings rule for that time in @var{zone} (which may
1308 differ from what @var{sbd-time} had). The easiest way to think of
1309 this is that @var{sbd-time} plus @var{zone} converts to the integer
1310 UTC time, then a @code{localtime} is applied to get the normal
1311 presentation of that time, in @var{zone}.
1312 @end deffn
1313
1314 @deffn {Scheme Procedure} tzset
1315 @deffnx {C Function} scm_tzset ()
1316 Initialize the timezone from the @env{TZ} environment variable
1317 or the system default. It's not usually necessary to call this procedure
1318 since it's done automatically by other procedures that depend on the
1319 timezone.
1320 @end deffn
1321
1322 @deffn {Scheme Procedure} strftime format tm
1323 @deffnx {C Function} scm_strftime (format, tm)
1324 @cindex time formatting
1325 Return a string which is broken-down time structure @var{tm} formatted
1326 according to the given @var{format} string.
1327
1328 @var{format} contains field specifications introduced by a @samp{%}
1329 character. See @ref{Formatting Calendar Time,,, libc, The GNU C
1330 Library Reference Manual}, or @samp{man 3 strftime}, for the available
1331 formatting.
1332
1333 @lisp
1334 (strftime "%c" (localtime (current-time)))
1335 @result{} "Mon Mar 11 20:17:43 2002"
1336 @end lisp
1337
1338 If @code{setlocale} has been called (@pxref{Locales}), month and day
1339 names are from the current locale and in the locale character set.
1340 @end deffn
1341
1342 @deffn {Scheme Procedure} strptime format string
1343 @deffnx {C Function} scm_strptime (format, string)
1344 @cindex time parsing
1345 Performs the reverse action to @code{strftime}, parsing
1346 @var{string} according to the specification supplied in
1347 @var{format}. The interpretation of month and day names is
1348 dependent on the current locale. The value returned is a pair.
1349 The @acronym{CAR} has an object with time components
1350 in the form returned by @code{localtime} or @code{gmtime},
1351 but the time zone components
1352 are not usefully set.
1353 The @acronym{CDR} reports the number of characters from @var{string}
1354 which were used for the conversion.
1355 @end deffn
1356
1357 @defvar internal-time-units-per-second
1358 The value of this variable is the number of time units per second
1359 reported by the following procedures.
1360 @end defvar
1361
1362 @deffn {Scheme Procedure} times
1363 @deffnx {C Function} scm_times ()
1364 Return an object with information about real and processor
1365 time. The following procedures accept such an object as an
1366 argument and return a selected component:
1367
1368 @deffn {Scheme Procedure} tms:clock tms
1369 The current real time, expressed as time units relative to an
1370 arbitrary base.
1371 @end deffn
1372 @deffn {Scheme Procedure} tms:utime tms
1373 The CPU time units used by the calling process.
1374 @end deffn
1375 @deffn {Scheme Procedure} tms:stime tms
1376 The CPU time units used by the system on behalf of the calling
1377 process.
1378 @end deffn
1379 @deffn {Scheme Procedure} tms:cutime tms
1380 The CPU time units used by terminated child processes of the
1381 calling process, whose status has been collected (e.g., using
1382 @code{waitpid}).
1383 @end deffn
1384 @deffn {Scheme Procedure} tms:cstime tms
1385 Similarly, the CPU times units used by the system on behalf of
1386 terminated child processes.
1387 @end deffn
1388 @end deffn
1389
1390 @deffn {Scheme Procedure} get-internal-real-time
1391 @deffnx {C Function} scm_get_internal_real_time ()
1392 Return the number of time units since the interpreter was
1393 started.
1394 @end deffn
1395
1396 @deffn {Scheme Procedure} get-internal-run-time
1397 @deffnx {C Function} scm_get_internal_run_time ()
1398 Return the number of time units of processor time used by the
1399 interpreter. Both @emph{system} and @emph{user} time are
1400 included but subprocesses are not.
1401 @end deffn
1402
1403 @node Runtime Environment
1404 @subsection Runtime Environment
1405
1406 @deffn {Scheme Procedure} program-arguments
1407 @deffnx {Scheme Procedure} command-line
1408 @deffnx {Scheme Procedure} set-program-arguments
1409 @deffnx {C Function} scm_program_arguments ()
1410 @deffnx {C Function} scm_set_program_arguments_scm (lst)
1411 @cindex command line
1412 @cindex program arguments
1413 Get the command line arguments passed to Guile, or set new arguments.
1414
1415 The arguments are a list of strings, the first of which is the invoked
1416 program name. This is just @nicode{"guile"} (or the executable path)
1417 when run interactively, or it's the script name when running a script
1418 with @option{-s} (@pxref{Invoking Guile}).
1419
1420 @example
1421 guile -L /my/extra/dir -s foo.scm abc def
1422
1423 (program-arguments) @result{} ("foo.scm" "abc" "def")
1424 @end example
1425
1426 @code{set-program-arguments} allows a library module or similar to
1427 modify the arguments, for example to strip options it recognises,
1428 leaving the rest for the mainline.
1429
1430 The argument list is held in a fluid, which means it's separate for
1431 each thread. Neither the list nor the strings within it are copied at
1432 any point and normally should not be mutated.
1433
1434 The two names @code{program-arguments} and @code{command-line} are an
1435 historical accident, they both do exactly the same thing. The name
1436 @code{scm_set_program_arguments_scm} has an extra @code{_scm} on the
1437 end to avoid clashing with the C function below.
1438 @end deffn
1439
1440 @deftypefn {C Function} void scm_set_program_arguments (int argc, char **argv, char *first)
1441 @cindex command line
1442 @cindex program arguments
1443 Set the list of command line arguments for @code{program-arguments}
1444 and @code{command-line} above.
1445
1446 @var{argv} is an array of null-terminated strings, as in a C
1447 @code{main} function. @var{argc} is the number of strings in
1448 @var{argv}, or if it's negative then a @code{NULL} in @var{argv} marks
1449 its end.
1450
1451 @var{first} is an extra string put at the start of the arguments, or
1452 @code{NULL} for no such extra. This is a convenient way to pass the
1453 program name after advancing @var{argv} to strip option arguments.
1454 Eg.@:
1455
1456 @example
1457 @{
1458 char *progname = argv[0];
1459 for (argv++; argv[0] != NULL && argv[0][0] == '-'; argv++)
1460 @{
1461 /* munch option ... */
1462 @}
1463 /* remaining args for scheme level use */
1464 scm_set_program_arguments (-1, argv, progname);
1465 @}
1466 @end example
1467
1468 This sort of thing is often done at startup under
1469 @code{scm_boot_guile} with options handled at the C level removed.
1470 The given strings are all copied, so the C data is not accessed again
1471 once @code{scm_set_program_arguments} returns.
1472 @end deftypefn
1473
1474 @deffn {Scheme Procedure} getenv name
1475 @deffnx {C Function} scm_getenv (name)
1476 @cindex environment
1477 Looks up the string @var{name} in the current environment. The return
1478 value is @code{#f} unless a string of the form @code{NAME=VALUE} is
1479 found, in which case the string @code{VALUE} is returned.
1480 @end deffn
1481
1482 @deffn {Scheme Procedure} setenv name value
1483 Modifies the environment of the current process, which is
1484 also the default environment inherited by child processes.
1485
1486 If @var{value} is @code{#f}, then @var{name} is removed from the
1487 environment. Otherwise, the string @var{name}=@var{value} is added
1488 to the environment, replacing any existing string with name matching
1489 @var{name}.
1490
1491 The return value is unspecified.
1492 @end deffn
1493
1494 @deffn {Scheme Procedure} unsetenv name
1495 Remove variable @var{name} from the environment. The
1496 name can not contain a @samp{=} character.
1497 @end deffn
1498
1499 @deffn {Scheme Procedure} environ [env]
1500 @deffnx {C Function} scm_environ (env)
1501 If @var{env} is omitted, return the current environment (in the
1502 Unix sense) as a list of strings. Otherwise set the current
1503 environment, which is also the default environment for child
1504 processes, to the supplied list of strings. Each member of
1505 @var{env} should be of the form @var{name}=@var{value} and values of
1506 @var{name} should not be duplicated. If @var{env} is supplied
1507 then the return value is unspecified.
1508 @end deffn
1509
1510 @deffn {Scheme Procedure} putenv str
1511 @deffnx {C Function} scm_putenv (str)
1512 Modifies the environment of the current process, which is
1513 also the default environment inherited by child processes.
1514
1515 If @var{str} is of the form @code{NAME=VALUE} then it will be written
1516 directly into the environment, replacing any existing environment string
1517 with
1518 name matching @code{NAME}. If @var{str} does not contain an equal
1519 sign, then any existing string with name matching @var{str} will
1520 be removed.
1521
1522 The return value is unspecified.
1523 @end deffn
1524
1525
1526 @node Processes
1527 @subsection Processes
1528 @cindex processes
1529 @cindex child processes
1530
1531 @findex cd
1532 @deffn {Scheme Procedure} chdir str
1533 @deffnx {C Function} scm_chdir (str)
1534 @cindex current directory
1535 Change the current working directory to @var{str}.
1536 The return value is unspecified.
1537 @end deffn
1538
1539 @findex pwd
1540 @deffn {Scheme Procedure} getcwd
1541 @deffnx {C Function} scm_getcwd ()
1542 Return the name of the current working directory.
1543 @end deffn
1544
1545 @deffn {Scheme Procedure} umask [mode]
1546 @deffnx {C Function} scm_umask (mode)
1547 If @var{mode} is omitted, returns a decimal number representing the
1548 current file creation mask. Otherwise the file creation mask is set
1549 to @var{mode} and the previous value is returned. @xref{Setting
1550 Permissions,,Assigning File Permissions,libc,The GNU C Library
1551 Reference Manual}, for more on how to use umasks.
1552
1553 E.g., @code{(umask #o022)} sets the mask to octal 22/decimal 18.
1554 @end deffn
1555
1556 @deffn {Scheme Procedure} chroot path
1557 @deffnx {C Function} scm_chroot (path)
1558 Change the root directory to that specified in @var{path}.
1559 This directory will be used for path names beginning with
1560 @file{/}. The root directory is inherited by all children
1561 of the current process. Only the superuser may change the
1562 root directory.
1563 @end deffn
1564
1565 @deffn {Scheme Procedure} getpid
1566 @deffnx {C Function} scm_getpid ()
1567 Return an integer representing the current process ID.
1568 @end deffn
1569
1570 @deffn {Scheme Procedure} getgroups
1571 @deffnx {C Function} scm_getgroups ()
1572 Return a vector of integers representing the current
1573 supplementary group IDs.
1574 @end deffn
1575
1576 @deffn {Scheme Procedure} getppid
1577 @deffnx {C Function} scm_getppid ()
1578 Return an integer representing the process ID of the parent
1579 process.
1580 @end deffn
1581
1582 @deffn {Scheme Procedure} getuid
1583 @deffnx {C Function} scm_getuid ()
1584 Return an integer representing the current real user ID.
1585 @end deffn
1586
1587 @deffn {Scheme Procedure} getgid
1588 @deffnx {C Function} scm_getgid ()
1589 Return an integer representing the current real group ID.
1590 @end deffn
1591
1592 @deffn {Scheme Procedure} geteuid
1593 @deffnx {C Function} scm_geteuid ()
1594 Return an integer representing the current effective user ID.
1595 If the system does not support effective IDs, then the real ID
1596 is returned. @code{(provided? 'EIDs)} reports whether the
1597 system supports effective IDs.
1598 @end deffn
1599
1600 @deffn {Scheme Procedure} getegid
1601 @deffnx {C Function} scm_getegid ()
1602 Return an integer representing the current effective group ID.
1603 If the system does not support effective IDs, then the real ID
1604 is returned. @code{(provided? 'EIDs)} reports whether the
1605 system supports effective IDs.
1606 @end deffn
1607
1608 @deffn {Scheme Procedure} setgroups vec
1609 @deffnx {C Function} scm_setgroups (vec)
1610 Set the current set of supplementary group IDs to the integers in the
1611 given vector @var{vec}. The return value is unspecified.
1612
1613 Generally only the superuser can set the process group IDs
1614 (@pxref{Setting Groups, Setting the Group IDs,, libc, The GNU C
1615 Library Reference Manual}).
1616 @end deffn
1617
1618 @deffn {Scheme Procedure} setuid id
1619 @deffnx {C Function} scm_setuid (id)
1620 Sets both the real and effective user IDs to the integer @var{id}, provided
1621 the process has appropriate privileges.
1622 The return value is unspecified.
1623 @end deffn
1624
1625 @deffn {Scheme Procedure} setgid id
1626 @deffnx {C Function} scm_setgid (id)
1627 Sets both the real and effective group IDs to the integer @var{id}, provided
1628 the process has appropriate privileges.
1629 The return value is unspecified.
1630 @end deffn
1631
1632 @deffn {Scheme Procedure} seteuid id
1633 @deffnx {C Function} scm_seteuid (id)
1634 Sets the effective user ID to the integer @var{id}, provided the process
1635 has appropriate privileges. If effective IDs are not supported, the
1636 real ID is set instead---@code{(provided? 'EIDs)} reports whether the
1637 system supports effective IDs.
1638 The return value is unspecified.
1639 @end deffn
1640
1641 @deffn {Scheme Procedure} setegid id
1642 @deffnx {C Function} scm_setegid (id)
1643 Sets the effective group ID to the integer @var{id}, provided the process
1644 has appropriate privileges. If effective IDs are not supported, the
1645 real ID is set instead---@code{(provided? 'EIDs)} reports whether the
1646 system supports effective IDs.
1647 The return value is unspecified.
1648 @end deffn
1649
1650 @deffn {Scheme Procedure} getpgrp
1651 @deffnx {C Function} scm_getpgrp ()
1652 Return an integer representing the current process group ID.
1653 This is the @acronym{POSIX} definition, not @acronym{BSD}.
1654 @end deffn
1655
1656 @deffn {Scheme Procedure} setpgid pid pgid
1657 @deffnx {C Function} scm_setpgid (pid, pgid)
1658 Move the process @var{pid} into the process group @var{pgid}. @var{pid} or
1659 @var{pgid} must be integers: they can be zero to indicate the ID of the
1660 current process.
1661 Fails on systems that do not support job control.
1662 The return value is unspecified.
1663 @end deffn
1664
1665 @deffn {Scheme Procedure} setsid
1666 @deffnx {C Function} scm_setsid ()
1667 Creates a new session. The current process becomes the session leader
1668 and is put in a new process group. The process will be detached
1669 from its controlling terminal if it has one.
1670 The return value is an integer representing the new process group ID.
1671 @end deffn
1672
1673 @deffn {Scheme Procedure} getsid pid
1674 @deffnx {C Function} scm_getsid (pid)
1675 Returns the session ID of process @var{pid}. (The session
1676 ID of a process is the process group ID of its session leader.)
1677 @end deffn
1678
1679 @deffn {Scheme Procedure} waitpid pid [options]
1680 @deffnx {C Function} scm_waitpid (pid, options)
1681 This procedure collects status information from a child process which
1682 has terminated or (optionally) stopped. Normally it will
1683 suspend the calling process until this can be done. If more than one
1684 child process is eligible then one will be chosen by the operating system.
1685
1686 The value of @var{pid} determines the behaviour:
1687
1688 @table @asis
1689 @item @var{pid} greater than 0
1690 Request status information from the specified child process.
1691 @item @var{pid} equal to -1 or @code{WAIT_ANY}
1692 @vindex WAIT_ANY
1693 Request status information for any child process.
1694 @item @var{pid} equal to 0 or @code{WAIT_MYPGRP}
1695 @vindex WAIT_MYPGRP
1696 Request status information for any child process in the current process
1697 group.
1698 @item @var{pid} less than -1
1699 Request status information for any child process whose process group ID
1700 is @minus{}@var{pid}.
1701 @end table
1702
1703 The @var{options} argument, if supplied, should be the bitwise OR of the
1704 values of zero or more of the following variables:
1705
1706 @defvar WNOHANG
1707 Return immediately even if there are no child processes to be collected.
1708 @end defvar
1709
1710 @defvar WUNTRACED
1711 Report status information for stopped processes as well as terminated
1712 processes.
1713 @end defvar
1714
1715 The return value is a pair containing:
1716
1717 @enumerate
1718 @item
1719 The process ID of the child process, or 0 if @code{WNOHANG} was
1720 specified and no process was collected.
1721 @item
1722 The integer status value.
1723 @end enumerate
1724 @end deffn
1725
1726 The following three
1727 functions can be used to decode the process status code returned
1728 by @code{waitpid}.
1729
1730 @deffn {Scheme Procedure} status:exit-val status
1731 @deffnx {C Function} scm_status_exit_val (status)
1732 Return the exit status value, as would be set if a process
1733 ended normally through a call to @code{exit} or @code{_exit},
1734 if any, otherwise @code{#f}.
1735 @end deffn
1736
1737 @deffn {Scheme Procedure} status:term-sig status
1738 @deffnx {C Function} scm_status_term_sig (status)
1739 Return the signal number which terminated the process, if any,
1740 otherwise @code{#f}.
1741 @end deffn
1742
1743 @deffn {Scheme Procedure} status:stop-sig status
1744 @deffnx {C Function} scm_status_stop_sig (status)
1745 Return the signal number which stopped the process, if any,
1746 otherwise @code{#f}.
1747 @end deffn
1748
1749 @deffn {Scheme Procedure} system [cmd]
1750 @deffnx {C Function} scm_system (cmd)
1751 Execute @var{cmd} using the operating system's ``command
1752 processor''. Under Unix this is usually the default shell
1753 @code{sh}. The value returned is @var{cmd}'s exit status as
1754 returned by @code{waitpid}, which can be interpreted using the
1755 functions above.
1756
1757 If @code{system} is called without arguments, return a boolean
1758 indicating whether the command processor is available.
1759 @end deffn
1760
1761 @deffn {Scheme Procedure} system* arg1 arg2 @dots{}
1762 @deffnx {C Function} scm_system_star (args)
1763 Execute the command indicated by @var{arg1} @var{arg2} @enddots{}. The
1764 first element must be a string indicating the command to be executed,
1765 and the remaining items must be strings representing each of the
1766 arguments to that command.
1767
1768 This function returns the exit status of the command as provided by
1769 @code{waitpid}. This value can be handled with @code{status:exit-val}
1770 and the related functions.
1771
1772 @code{system*} is similar to @code{system}, but accepts only one
1773 string per-argument, and performs no shell interpretation. The
1774 command is executed using fork and execlp. Accordingly this function
1775 may be safer than @code{system} in situations where shell
1776 interpretation is not required.
1777
1778 Example: (system* "echo" "foo" "bar")
1779 @end deffn
1780
1781 @deffn {Scheme Procedure} quit [status]
1782 @deffnx {Scheme Procedure} exit [status]
1783 Terminate the current process with proper unwinding of the Scheme stack.
1784 The exit status zero if @var{status} is not supplied. If @var{status}
1785 is supplied, and it is an integer, that integer is used as the exit
1786 status. If @var{status} is @code{#t} or @code{#f}, the exit status is 0
1787 or 1, respectively.
1788
1789 The procedure @code{exit} is an alias of @code{quit}. They have the
1790 same functionality.
1791 @end deffn
1792
1793 @deffn {Scheme Procedure} primitive-exit [status]
1794 @deffnx {Scheme Procedure} primitive-_exit [status]
1795 @deffnx {C Function} scm_primitive_exit (status)
1796 @deffnx {C Function} scm_primitive__exit (status)
1797 Terminate the current process without unwinding the Scheme stack. The
1798 exit status is @var{status} if supplied, otherwise zero.
1799
1800 @code{primitive-exit} uses the C @code{exit} function and hence runs
1801 usual C level cleanups (flush output streams, call @code{atexit}
1802 functions, etc, see @ref{Normal Termination,,, libc, The GNU C Library
1803 Reference Manual})).
1804
1805 @code{primitive-_exit} is the @code{_exit} system call
1806 (@pxref{Termination Internals,,, libc, The GNU C Library Reference
1807 Manual}). This terminates the program immediately, with neither
1808 Scheme-level nor C-level cleanups.
1809
1810 The typical use for @code{primitive-_exit} is from a child process
1811 created with @code{primitive-fork}. For example in a Gdk program the
1812 child process inherits the X server connection and a C-level
1813 @code{atexit} cleanup which will close that connection. But closing
1814 in the child would upset the protocol in the parent, so
1815 @code{primitive-_exit} should be used to exit without that.
1816 @end deffn
1817
1818 @deffn {Scheme Procedure} execl filename arg @dots{}
1819 @deffnx {C Function} scm_execl (filename, args)
1820 Executes the file named by @var{filename} as a new process image.
1821 The remaining arguments are supplied to the process; from a C program
1822 they are accessible as the @code{argv} argument to @code{main}.
1823 Conventionally the first @var{arg} is the same as @var{filename}.
1824 All arguments must be strings.
1825
1826 If @var{arg} is missing, @var{filename} is executed with a null
1827 argument list, which may have system-dependent side-effects.
1828
1829 This procedure is currently implemented using the @code{execv} system
1830 call, but we call it @code{execl} because of its Scheme calling interface.
1831 @end deffn
1832
1833 @deffn {Scheme Procedure} execlp filename arg @dots{}
1834 @deffnx {C Function} scm_execlp (filename, args)
1835 Similar to @code{execl}, however if
1836 @var{filename} does not contain a slash
1837 then the file to execute will be located by searching the
1838 directories listed in the @code{PATH} environment variable.
1839
1840 This procedure is currently implemented using the @code{execvp} system
1841 call, but we call it @code{execlp} because of its Scheme calling interface.
1842 @end deffn
1843
1844 @deffn {Scheme Procedure} execle filename env arg @dots{}
1845 @deffnx {C Function} scm_execle (filename, env, args)
1846 Similar to @code{execl}, but the environment of the new process is
1847 specified by @var{env}, which must be a list of strings as returned by the
1848 @code{environ} procedure.
1849
1850 This procedure is currently implemented using the @code{execve} system
1851 call, but we call it @code{execle} because of its Scheme calling interface.
1852 @end deffn
1853
1854 @deffn {Scheme Procedure} primitive-fork
1855 @deffnx {C Function} scm_fork ()
1856 Creates a new ``child'' process by duplicating the current ``parent'' process.
1857 In the child the return value is 0. In the parent the return value is
1858 the integer process ID of the child.
1859
1860 Note that it is unsafe to fork a process that has multiple threads
1861 running, as only the thread that calls @code{primitive-fork} will
1862 persist in the child. Any resources that other threads held, such as
1863 locked mutexes or open file descriptors, are lost. Indeed, @acronym{POSIX}
1864 specifies that only async-signal-safe procedures are safe to call after
1865 a multithreaded fork, which is a very limited set. Guile issues a
1866 warning if it detects a fork from a multi-threaded program.
1867
1868 If you are going to @code{exec} soon after forking, the procedures in
1869 @code{(ice-9 popen)} may be useful to you, as they fork and exec within
1870 an async-signal-safe function carefully written to ensure robust program
1871 behavior, even in the presence of threads. @xref{Pipes}, for more.
1872
1873 This procedure has been renamed from @code{fork} to avoid a naming conflict
1874 with the scsh fork.
1875 @end deffn
1876
1877 @deffn {Scheme Procedure} nice incr
1878 @deffnx {C Function} scm_nice (incr)
1879 @cindex process priority
1880 Increment the priority of the current process by @var{incr}. A higher
1881 priority value means that the process runs less often.
1882 The return value is unspecified.
1883 @end deffn
1884
1885 @deffn {Scheme Procedure} setpriority which who prio
1886 @deffnx {C Function} scm_setpriority (which, who, prio)
1887 @vindex PRIO_PROCESS
1888 @vindex PRIO_PGRP
1889 @vindex PRIO_USER
1890 Set the scheduling priority of the process, process group
1891 or user, as indicated by @var{which} and @var{who}. @var{which}
1892 is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
1893 or @code{PRIO_USER}, and @var{who} is interpreted relative to
1894 @var{which} (a process identifier for @code{PRIO_PROCESS},
1895 process group identifier for @code{PRIO_PGRP}, and a user
1896 identifier for @code{PRIO_USER}. A zero value of @var{who}
1897 denotes the current process, process group, or user.
1898 @var{prio} is a value in the range [@minus{}20,20]. The default
1899 priority is 0; lower priorities (in numerical terms) cause more
1900 favorable scheduling. Sets the priority of all of the specified
1901 processes. Only the super-user may lower priorities. The return
1902 value is not specified.
1903 @end deffn
1904
1905 @deffn {Scheme Procedure} getpriority which who
1906 @deffnx {C Function} scm_getpriority (which, who)
1907 @vindex PRIO_PROCESS
1908 @vindex PRIO_PGRP
1909 @vindex PRIO_USER
1910 Return the scheduling priority of the process, process group
1911 or user, as indicated by @var{which} and @var{who}. @var{which}
1912 is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
1913 or @code{PRIO_USER}, and @var{who} should be interpreted depending on
1914 @var{which} (a process identifier for @code{PRIO_PROCESS},
1915 process group identifier for @code{PRIO_PGRP}, and a user
1916 identifier for @code{PRIO_USER}). A zero value of @var{who}
1917 denotes the current process, process group, or user. Return
1918 the highest priority (lowest numerical value) of any of the
1919 specified processes.
1920 @end deffn
1921
1922 @cindex affinity, CPU
1923
1924 @deffn {Scheme Procedure} getaffinity pid
1925 @deffnx {C Function} scm_getaffinity (pid)
1926 Return a bitvector representing the CPU affinity mask for
1927 process @var{pid}. Each CPU the process has affinity with
1928 has its corresponding bit set in the returned bitvector.
1929 The number of bits set is a good estimate of how many CPUs
1930 Guile can use without stepping on other processes' toes.
1931
1932 Currently this procedure is only defined on GNU variants
1933 (@pxref{CPU Affinity, @code{sched_getaffinity},, libc, The
1934 GNU C Library Reference Manual}).
1935 @end deffn
1936
1937 @deffn {Scheme Procedure} setaffinity pid mask
1938 @deffnx {C Function} scm_setaffinity (pid, mask)
1939 Install the CPU affinity mask @var{mask}, a bitvector, for
1940 the process or thread with ID @var{pid}. The return value
1941 is unspecified.
1942
1943 Currently this procedure is only defined on GNU variants
1944 (@pxref{CPU Affinity, @code{sched_setaffinity},, libc, The
1945 GNU C Library Reference Manual}).
1946 @end deffn
1947
1948 @deffn {Scheme Procedure} total-processor-count
1949 @deffnx {C Function} scm_total_processor_count ()
1950 Return the total number of processors of the machine, which
1951 is guaranteed to be at least 1. A ``processor'' here is a
1952 thread execution unit, which can be either:
1953
1954 @itemize
1955 @item an execution core in a (possibly multi-core) chip, in a
1956 (possibly multi- chip) module, in a single computer, or
1957 @item a thread execution unit inside a core in the case of
1958 @dfn{hyper-threaded} CPUs.
1959 @end itemize
1960
1961 Which of the two definitions is used, is unspecified.
1962 @end deffn
1963
1964 @deffn {Scheme Procedure} current-processor-count
1965 @deffnx {C Function} scm_current_processor_count ()
1966 Like @code{total-processor-count}, but return the number of
1967 processors available to the current process. See
1968 @code{setaffinity} and @code{getaffinity} for more
1969 information.
1970 @end deffn
1971
1972
1973 @node Signals
1974 @subsection Signals
1975 @cindex signal
1976
1977 The following procedures raise, handle and wait for signals.
1978
1979 Scheme code signal handlers are run via a system async (@pxref{System
1980 asyncs}), so they're called in the handler's thread at the next safe
1981 opportunity. Generally this is after any currently executing
1982 primitive procedure finishes (which could be a long time for
1983 primitives that wait for an external event).
1984
1985 @deffn {Scheme Procedure} kill pid sig
1986 @deffnx {C Function} scm_kill (pid, sig)
1987 Sends a signal to the specified process or group of processes.
1988
1989 @var{pid} specifies the processes to which the signal is sent:
1990
1991 @table @asis
1992 @item @var{pid} greater than 0
1993 The process whose identifier is @var{pid}.
1994 @item @var{pid} equal to 0
1995 All processes in the current process group.
1996 @item @var{pid} less than -1
1997 The process group whose identifier is -@var{pid}
1998 @item @var{pid} equal to -1
1999 If the process is privileged, all processes except for some special
2000 system processes. Otherwise, all processes with the current effective
2001 user ID.
2002 @end table
2003
2004 @var{sig} should be specified using a variable corresponding to
2005 the Unix symbolic name, e.g.,
2006
2007 @defvar SIGHUP
2008 Hang-up signal.
2009 @end defvar
2010
2011 @defvar SIGINT
2012 Interrupt signal.
2013 @end defvar
2014
2015 A full list of signals on the GNU system may be found in @ref{Standard
2016 Signals,,,libc,The GNU C Library Reference Manual}.
2017 @end deffn
2018
2019 @deffn {Scheme Procedure} raise sig
2020 @deffnx {C Function} scm_raise (sig)
2021 Sends a specified signal @var{sig} to the current process, where
2022 @var{sig} is as described for the @code{kill} procedure.
2023 @end deffn
2024
2025 @deffn {Scheme Procedure} sigaction signum [handler [flags [thread]]]
2026 @deffnx {C Function} scm_sigaction (signum, handler, flags)
2027 @deffnx {C Function} scm_sigaction_for_thread (signum, handler, flags, thread)
2028 Install or report the signal handler for a specified signal.
2029
2030 @var{signum} is the signal number, which can be specified using the value
2031 of variables such as @code{SIGINT}.
2032
2033 If @var{handler} is omitted, @code{sigaction} returns a pair: the
2034 @acronym{CAR} is the current signal hander, which will be either an
2035 integer with the value @code{SIG_DFL} (default action) or
2036 @code{SIG_IGN} (ignore), or the Scheme procedure which handles the
2037 signal, or @code{#f} if a non-Scheme procedure handles the signal.
2038 The @acronym{CDR} contains the current @code{sigaction} flags for the
2039 handler.
2040
2041 If @var{handler} is provided, it is installed as the new handler for
2042 @var{signum}. @var{handler} can be a Scheme procedure taking one
2043 argument, or the value of @code{SIG_DFL} (default action) or
2044 @code{SIG_IGN} (ignore), or @code{#f} to restore whatever signal handler
2045 was installed before @code{sigaction} was first used. When a scheme
2046 procedure has been specified, that procedure will run in the given
2047 @var{thread}. When no thread has been given, the thread that made this
2048 call to @code{sigaction} is used.
2049
2050 @var{flags} is a @code{logior} (@pxref{Bitwise Operations}) of the
2051 following (where provided by the system), or @code{0} for none.
2052
2053 @defvar SA_NOCLDSTOP
2054 By default, @code{SIGCHLD} is signalled when a child process stops
2055 (ie.@: receives @code{SIGSTOP}), and when a child process terminates.
2056 With the @code{SA_NOCLDSTOP} flag, @code{SIGCHLD} is only signalled
2057 for termination, not stopping.
2058
2059 @code{SA_NOCLDSTOP} has no effect on signals other than
2060 @code{SIGCHLD}.
2061 @end defvar
2062
2063 @defvar SA_RESTART
2064 If a signal occurs while in a system call, deliver the signal then
2065 restart the system call (as opposed to returning an @code{EINTR} error
2066 from that call).
2067 @end defvar
2068
2069 The return value is a pair with information about the old handler as
2070 described above.
2071
2072 This interface does not provide access to the ``signal blocking''
2073 facility. Maybe this is not needed, since the thread support may
2074 provide solutions to the problem of consistent access to data
2075 structures.
2076 @end deffn
2077
2078 @deffn {Scheme Procedure} restore-signals
2079 @deffnx {C Function} scm_restore_signals ()
2080 Return all signal handlers to the values they had before any call to
2081 @code{sigaction} was made. The return value is unspecified.
2082 @end deffn
2083
2084 @deffn {Scheme Procedure} alarm i
2085 @deffnx {C Function} scm_alarm (i)
2086 Set a timer to raise a @code{SIGALRM} signal after the specified
2087 number of seconds (an integer). It's advisable to install a signal
2088 handler for
2089 @code{SIGALRM} beforehand, since the default action is to terminate
2090 the process.
2091
2092 The return value indicates the time remaining for the previous alarm,
2093 if any. The new value replaces the previous alarm. If there was
2094 no previous alarm, the return value is zero.
2095 @end deffn
2096
2097 @deffn {Scheme Procedure} pause
2098 @deffnx {C Function} scm_pause ()
2099 Pause the current process (thread?) until a signal arrives whose
2100 action is to either terminate the current process or invoke a
2101 handler procedure. The return value is unspecified.
2102 @end deffn
2103
2104 @deffn {Scheme Procedure} sleep secs
2105 @deffnx {Scheme Procedure} usleep usecs
2106 @deffnx {C Function} scm_sleep (secs)
2107 @deffnx {C Function} scm_usleep (usecs)
2108 Wait the given period @var{secs} seconds or @var{usecs} microseconds
2109 (both integers). If a signal arrives the wait stops and the return
2110 value is the time remaining, in seconds or microseconds respectively.
2111 If the period elapses with no signal the return is zero.
2112
2113 On most systems the process scheduler is not microsecond accurate and
2114 the actual period slept by @code{usleep} might be rounded to a system
2115 clock tick boundary, which might be 10 milliseconds for instance.
2116
2117 See @code{scm_std_sleep} and @code{scm_std_usleep} for equivalents at
2118 the C level (@pxref{Blocking}).
2119 @end deffn
2120
2121 @deffn {Scheme Procedure} getitimer which_timer
2122 @deffnx {Scheme Procedure} setitimer which_timer interval_seconds interval_microseconds periodic_seconds periodic_microseconds
2123 @deffnx {C Function} scm_getitimer (which_timer)
2124 @deffnx {C Function} scm_setitimer (which_timer, interval_seconds, interval_microseconds, periodic_seconds, periodic_microseconds)
2125 Get or set the periods programmed in certain system timers. These
2126 timers have a current interval value which counts down and on reaching
2127 zero raises a signal. An optional periodic value can be set to
2128 restart from there each time, for periodic operation.
2129 @var{which_timer} is one of the following values
2130
2131 @defvar ITIMER_REAL
2132 A real-time timer, counting down elapsed real time. At zero it raises
2133 @code{SIGALRM}. This is like @code{alarm} above, but with a higher
2134 resolution period.
2135 @end defvar
2136
2137 @defvar ITIMER_VIRTUAL
2138 A virtual-time timer, counting down while the current process is
2139 actually using CPU. At zero it raises @code{SIGVTALRM}.
2140 @end defvar
2141
2142 @defvar ITIMER_PROF
2143 A profiling timer, counting down while the process is running (like
2144 @code{ITIMER_VIRTUAL}) and also while system calls are running on the
2145 process's behalf. At zero it raises a @code{SIGPROF}.
2146
2147 This timer is intended for profiling where a program is spending its
2148 time (by looking where it is when the timer goes off).
2149 @end defvar
2150
2151 @code{getitimer} returns the current timer value and its programmed
2152 restart value, as a list containing two pairs. Each pair is a time in
2153 seconds and microseconds: @code{((@var{interval_secs}
2154 . @var{interval_usecs}) (@var{periodic_secs}
2155 . @var{periodic_usecs}))}.
2156
2157 @code{setitimer} sets the timer values similarly, in seconds and
2158 microseconds (which must be integers). The periodic value can be zero
2159 to have the timer run down just once. The return value is the timer's
2160 previous setting, in the same form as @code{getitimer} returns.
2161
2162 @example
2163 (setitimer ITIMER_REAL
2164 5 500000 ;; first SIGALRM in 5.5 seconds time
2165 2 0) ;; then repeat every 2 seconds
2166 @end example
2167
2168 Although the timers are programmed in microseconds, the actual
2169 accuracy might not be that high.
2170 @end deffn
2171
2172
2173 @node Terminals and Ptys
2174 @subsection Terminals and Ptys
2175
2176 @deffn {Scheme Procedure} isatty? port
2177 @deffnx {C Function} scm_isatty_p (port)
2178 @cindex terminal
2179 Return @code{#t} if @var{port} is using a serial non--file
2180 device, otherwise @code{#f}.
2181 @end deffn
2182
2183 @deffn {Scheme Procedure} ttyname port
2184 @deffnx {C Function} scm_ttyname (port)
2185 @cindex terminal
2186 Return a string with the name of the serial terminal device
2187 underlying @var{port}.
2188 @end deffn
2189
2190 @deffn {Scheme Procedure} ctermid
2191 @deffnx {C Function} scm_ctermid ()
2192 @cindex terminal
2193 Return a string containing the file name of the controlling
2194 terminal for the current process.
2195 @end deffn
2196
2197 @deffn {Scheme Procedure} tcgetpgrp port
2198 @deffnx {C Function} scm_tcgetpgrp (port)
2199 @cindex process group
2200 Return the process group ID of the foreground process group
2201 associated with the terminal open on the file descriptor
2202 underlying @var{port}.
2203
2204 If there is no foreground process group, the return value is a
2205 number greater than 1 that does not match the process group ID
2206 of any existing process group. This can happen if all of the
2207 processes in the job that was formerly the foreground job have
2208 terminated, and no other job has yet been moved into the
2209 foreground.
2210 @end deffn
2211
2212 @deffn {Scheme Procedure} tcsetpgrp port pgid
2213 @deffnx {C Function} scm_tcsetpgrp (port, pgid)
2214 @cindex process group
2215 Set the foreground process group ID for the terminal used by the file
2216 descriptor underlying @var{port} to the integer @var{pgid}.
2217 The calling process
2218 must be a member of the same session as @var{pgid} and must have the same
2219 controlling terminal. The return value is unspecified.
2220 @end deffn
2221
2222 @node Pipes
2223 @subsection Pipes
2224 @cindex pipe
2225
2226 The following procedures are similar to the @code{popen} and
2227 @code{pclose} system routines. The code is in a separate ``popen''
2228 module@footnote{This module is only available on systems where the
2229 @code{fork} feature is provided (@pxref{Common Feature Symbols}).}:
2230
2231 @lisp
2232 (use-modules (ice-9 popen))
2233 @end lisp
2234
2235 @findex popen
2236 @deffn {Scheme Procedure} open-pipe command mode
2237 @deffnx {Scheme Procedure} open-pipe* mode prog [args...]
2238 Execute a command in a subprocess, with a pipe to it or from it, or
2239 with pipes in both directions.
2240
2241 @code{open-pipe} runs the shell @var{command} using @samp{/bin/sh -c}.
2242 @code{open-pipe*} executes @var{prog} directly, with the optional
2243 @var{args} arguments (all strings).
2244
2245 @var{mode} should be one of the following values. @code{OPEN_READ} is
2246 an input pipe, ie.@: to read from the subprocess. @code{OPEN_WRITE}
2247 is an output pipe, ie.@: to write to it.
2248
2249 @defvar OPEN_READ
2250 @defvarx OPEN_WRITE
2251 @defvarx OPEN_BOTH
2252 @end defvar
2253
2254 For an input pipe, the child's standard output is the pipe and
2255 standard input is inherited from @code{current-input-port}. For an
2256 output pipe, the child's standard input is the pipe and standard
2257 output is inherited from @code{current-output-port}. In all cases
2258 cases the child's standard error is inherited from
2259 @code{current-error-port} (@pxref{Default Ports}).
2260
2261 If those @code{current-X-ports} are not files of some kind, and hence
2262 don't have file descriptors for the child, then @file{/dev/null} is
2263 used instead.
2264
2265 Care should be taken with @code{OPEN_BOTH}, a deadlock will occur if
2266 both parent and child are writing, and waiting until the write
2267 completes before doing any reading. Each direction has
2268 @code{PIPE_BUF} bytes of buffering (@pxref{Ports and File
2269 Descriptors}), which will be enough for small writes, but not for say
2270 putting a big file through a filter.
2271 @end deffn
2272
2273 @deffn {Scheme Procedure} open-input-pipe command
2274 Equivalent to @code{open-pipe} with mode @code{OPEN_READ}.
2275
2276 @lisp
2277 (let* ((port (open-input-pipe "date --utc"))
2278 (str (read-line port)))
2279 (close-pipe port)
2280 str)
2281 @result{} "Mon Mar 11 20:10:44 UTC 2002"
2282 @end lisp
2283 @end deffn
2284
2285 @deffn {Scheme Procedure} open-output-pipe command
2286 Equivalent to @code{open-pipe} with mode @code{OPEN_WRITE}.
2287
2288 @lisp
2289 (let ((port (open-output-pipe "lpr")))
2290 (display "Something for the line printer.\n" port)
2291 (if (not (eqv? 0 (status:exit-val (close-pipe port))))
2292 (error "Cannot print")))
2293 @end lisp
2294 @end deffn
2295
2296 @deffn {Scheme Procedure} open-input-output-pipe command
2297 Equivalent to @code{open-pipe} with mode @code{OPEN_BOTH}.
2298 @end deffn
2299
2300 @findex pclose
2301 @deffn {Scheme Procedure} close-pipe port
2302 Close a pipe created by @code{open-pipe}, wait for the process to
2303 terminate, and return the wait status code. The status is as per
2304 @code{waitpid} and can be decoded with @code{status:exit-val} etc
2305 (@pxref{Processes})
2306 @end deffn
2307
2308 @sp 1
2309 @code{waitpid WAIT_ANY} should not be used when pipes are open, since
2310 it can reap a pipe's child process, causing an error from a subsequent
2311 @code{close-pipe}.
2312
2313 @code{close-port} (@pxref{Closing}) can close a pipe, but it doesn't
2314 reap the child process.
2315
2316 The garbage collector will close a pipe no longer in use, and reap the
2317 child process with @code{waitpid}. If the child hasn't yet terminated
2318 the garbage collector doesn't block, but instead checks again in the
2319 next GC.
2320
2321 Many systems have per-user and system-wide limits on the number of
2322 processes, and a system-wide limit on the number of pipes, so pipes
2323 should be closed explicitly when no longer needed, rather than letting
2324 the garbage collector pick them up at some later time.
2325
2326
2327 @node Networking
2328 @subsection Networking
2329 @cindex network
2330
2331 @menu
2332 * Network Address Conversion::
2333 * Network Databases::
2334 * Network Socket Address::
2335 * Network Sockets and Communication::
2336 * Internet Socket Examples::
2337 @end menu
2338
2339 @node Network Address Conversion
2340 @subsubsection Network Address Conversion
2341 @cindex network address
2342
2343 This section describes procedures which convert internet addresses
2344 between numeric and string formats.
2345
2346 @subsubheading IPv4 Address Conversion
2347 @cindex IPv4
2348
2349 An IPv4 Internet address is a 4-byte value, represented in Guile as an
2350 integer in host byte order, so that say ``0.0.0.1'' is 1, or
2351 ``1.0.0.0'' is 16777216.
2352
2353 Some underlying C functions use network byte order for addresses,
2354 Guile converts as necessary so that at the Scheme level its host byte
2355 order everywhere.
2356
2357 @defvar INADDR_ANY
2358 For a server, this can be used with @code{bind} (@pxref{Network
2359 Sockets and Communication}) to allow connections from any interface on
2360 the machine.
2361 @end defvar
2362
2363 @defvar INADDR_BROADCAST
2364 The broadcast address on the local network.
2365 @end defvar
2366
2367 @defvar INADDR_LOOPBACK
2368 The address of the local host using the loopback device, ie.@:
2369 @samp{127.0.0.1}.
2370 @end defvar
2371
2372 @c INADDR_NONE is defined in the code, but serves no purpose.
2373 @c inet_addr() returns it as an error indication, but that function
2374 @c isn't provided, for the good reason that inet_aton() does the same
2375 @c job and gives an unambiguous error indication. (INADDR_NONE is a
2376 @c valid 4-byte value, in glibc it's the same as INADDR_BROADCAST.)
2377 @c
2378 @c @defvar INADDR_NONE
2379 @c No address.
2380 @c @end defvar
2381
2382 @deffn {Scheme Procedure} inet-aton address
2383 @deffnx {C Function} scm_inet_aton (address)
2384 This function is deprecated in favor of @code{inet-pton}.
2385
2386 Convert an IPv4 Internet address from printable string
2387 (dotted decimal notation) to an integer. E.g.,
2388
2389 @lisp
2390 (inet-aton "127.0.0.1") @result{} 2130706433
2391 @end lisp
2392 @end deffn
2393
2394 @deffn {Scheme Procedure} inet-ntoa inetid
2395 @deffnx {C Function} scm_inet_ntoa (inetid)
2396 This function is deprecated in favor of @code{inet-ntop}.
2397
2398 Convert an IPv4 Internet address to a printable
2399 (dotted decimal notation) string. E.g.,
2400
2401 @lisp
2402 (inet-ntoa 2130706433) @result{} "127.0.0.1"
2403 @end lisp
2404 @end deffn
2405
2406 @deffn {Scheme Procedure} inet-netof address
2407 @deffnx {C Function} scm_inet_netof (address)
2408 Return the network number part of the given IPv4
2409 Internet address. E.g.,
2410
2411 @lisp
2412 (inet-netof 2130706433) @result{} 127
2413 @end lisp
2414 @end deffn
2415
2416 @deffn {Scheme Procedure} inet-lnaof address
2417 @deffnx {C Function} scm_lnaof (address)
2418 Return the local-address-with-network part of the given
2419 IPv4 Internet address, using the obsolete class A/B/C system.
2420 E.g.,
2421
2422 @lisp
2423 (inet-lnaof 2130706433) @result{} 1
2424 @end lisp
2425 @end deffn
2426
2427 @deffn {Scheme Procedure} inet-makeaddr net lna
2428 @deffnx {C Function} scm_inet_makeaddr (net, lna)
2429 Make an IPv4 Internet address by combining the network number
2430 @var{net} with the local-address-within-network number
2431 @var{lna}. E.g.,
2432
2433 @lisp
2434 (inet-makeaddr 127 1) @result{} 2130706433
2435 @end lisp
2436 @end deffn
2437
2438 @subsubheading IPv6 Address Conversion
2439 @cindex IPv6
2440
2441 An IPv6 Internet address is a 16-byte value, represented in Guile as
2442 an integer in host byte order, so that say ``::1'' is 1.
2443
2444 @deffn {Scheme Procedure} inet-ntop family address
2445 @deffnx {C Function} scm_inet_ntop (family, address)
2446 Convert a network address from an integer to a printable string.
2447 @var{family} can be @code{AF_INET} or @code{AF_INET6}. E.g.,
2448
2449 @lisp
2450 (inet-ntop AF_INET 2130706433) @result{} "127.0.0.1"
2451 (inet-ntop AF_INET6 (- (expt 2 128) 1))
2452 @result{} "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
2453 @end lisp
2454 @end deffn
2455
2456 @deffn {Scheme Procedure} inet-pton family address
2457 @deffnx {C Function} scm_inet_pton (family, address)
2458 Convert a string containing a printable network address to an integer
2459 address. @var{family} can be @code{AF_INET} or @code{AF_INET6}.
2460 E.g.,
2461
2462 @lisp
2463 (inet-pton AF_INET "127.0.0.1") @result{} 2130706433
2464 (inet-pton AF_INET6 "::1") @result{} 1
2465 @end lisp
2466 @end deffn
2467
2468
2469 @node Network Databases
2470 @subsubsection Network Databases
2471 @cindex network database
2472
2473 This section describes procedures which query various network databases.
2474 Care should be taken when using the database routines since they are not
2475 reentrant.
2476
2477 @subsubheading @code{getaddrinfo}
2478
2479 @cindex @code{addrinfo} object type
2480 @cindex host name lookup
2481 @cindex service name lookup
2482
2483 The @code{getaddrinfo} procedure maps host and service names to socket addresses
2484 and associated information in a protocol-independent way.
2485
2486 @deffn {Scheme Procedure} getaddrinfo name service [hint_flags [hint_family [hint_socktype [hint_protocol]]]]
2487 @deffnx {C Function} scm_getaddrinfo (name, service, hint_flags, hint_family, hint_socktype, hint_protocol)
2488 Return a list of @code{addrinfo} structures containing
2489 a socket address and associated information for host @var{name}
2490 and/or @var{service} to be used in creating a socket with
2491 which to address the specified service.
2492
2493 @example
2494 (let* ((ai (car (getaddrinfo "www.gnu.org" "http")))
2495 (s (socket (addrinfo:fam ai) (addrinfo:socktype ai)
2496 (addrinfo:protocol ai))))
2497 (connect s (addrinfo:addr ai))
2498 s)
2499 @end example
2500
2501 When @var{service} is omitted or is @code{#f}, return
2502 network-level addresses for @var{name}. When @var{name}
2503 is @code{#f} @var{service} must be provided and service
2504 locations local to the caller are returned.
2505
2506 Additional hints can be provided. When specified,
2507 @var{hint_flags} should be a bitwise-or of zero or more
2508 constants among the following:
2509
2510 @table @code
2511 @item AI_PASSIVE
2512 Socket address is intended for @code{bind}.
2513
2514 @item AI_CANONNAME
2515 Request for canonical host name, available via
2516 @code{addrinfo:canonname}. This makes sense mainly when
2517 DNS lookups are involved.
2518
2519 @item AI_NUMERICHOST
2520 Specifies that @var{name} is a numeric host address string
2521 (e.g., @code{"127.0.0.1"}), meaning that name resolution
2522 will not be used.
2523
2524 @item AI_NUMERICSERV
2525 Likewise, specifies that @var{service} is a numeric port
2526 string (e.g., @code{"80"}).
2527
2528 @item AI_ADDRCONFIG
2529 Return only addresses configured on the local system It is
2530 highly recommended to provide this flag when the returned
2531 socket addresses are to be used to make connections;
2532 otherwise, some of the returned addresses could be unreachable
2533 or use a protocol that is not supported.
2534
2535 @item AI_V4MAPPED
2536 When looking up IPv6 addresses, return mapped IPv4 addresses if
2537 there is no IPv6 address available at all.
2538
2539 @item AI_ALL
2540 If this flag is set along with @code{AI_V4MAPPED} when looking up IPv6
2541 addresses, return all IPv6 addresses as well as all IPv4 addresses, the latter
2542 mapped to IPv6 format.
2543 @end table
2544
2545 When given, @var{hint_family} should specify the requested
2546 address family, e.g., @code{AF_INET6}. Similarly,
2547 @var{hint_socktype} should specify the requested socket type
2548 (e.g., @code{SOCK_DGRAM}), and @var{hint_protocol} should
2549 specify the requested protocol (its value is interpreted
2550 as in calls to @code{socket}).
2551
2552 On error, an exception with key @code{getaddrinfo-error} is
2553 thrown, with an error code (an integer) as its argument:
2554
2555 @example
2556 (catch 'getaddrinfo-error
2557 (lambda ()
2558 (getaddrinfo "www.gnu.org" "gopher"))
2559 (lambda (key errcode)
2560 (cond ((= errcode EAI_SERVICE)
2561 (display "doesn't know about Gopher!\n"))
2562 ((= errcode EAI_NONAME)
2563 (display "www.gnu.org not found\\n"))
2564 (else
2565 (format #t "something wrong: ~a\n"
2566 (gai-strerror errcode))))))
2567 @end example
2568
2569 Error codes are:
2570
2571 @table @code
2572 @item EAI_AGAIN
2573 The name or service could not be resolved at this time. Future
2574 attempts may succeed.
2575
2576 @item EAI_BADFLAGS
2577 @var{hint_flags} contains an invalid value.
2578
2579 @item EAI_FAIL
2580 A non-recoverable error occurred when attempting to
2581 resolve the name.
2582
2583 @item EAI_FAMILY
2584 @var{hint_family} was not recognized.
2585
2586 @item EAI_NONAME
2587 Either @var{name} does not resolve for the supplied parameters,
2588 or neither @var{name} nor @var{service} were supplied.
2589
2590 @item EAI_NODATA
2591 This non-POSIX error code can be returned on some systems (GNU
2592 and Darwin, at least), for example when @var{name} is known
2593 but requests that were made turned out no data. Error handling
2594 code should be prepared to handle it when it is defined.
2595
2596 @item EAI_SERVICE
2597 @var{service} was not recognized for the specified socket type.
2598
2599 @item EAI_SOCKTYPE
2600 @var{hint_socktype} was not recognized.
2601
2602 @item EAI_SYSTEM
2603 A system error occurred. In C, the error code can be found in
2604 @code{errno}; this value is not accessible from Scheme, but in
2605 practice it provides little information about the actual error
2606 cause.
2607 @c See <http://bugs.gnu.org/13958>.
2608 @end table
2609
2610 Users are encouraged to read the
2611 @url{http://www.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html,
2612 "POSIX specification} for more details.
2613 @end deffn
2614
2615 The following procedures take an @code{addrinfo} object as returned by
2616 @code{getaddrinfo}:
2617
2618 @deffn {Scheme Procedure} addrinfo:flags ai
2619 Return flags for @var{ai} as a bitwise or of @code{AI_} values (see above).
2620 @end deffn
2621
2622 @deffn {Scheme Procedure} addrinfo:fam ai
2623 Return the address family of @var{ai} (a @code{AF_} value).
2624 @end deffn
2625
2626 @deffn {Scheme Procedure} addrinfo:socktype ai
2627 Return the socket type for @var{ai} (a @code{SOCK_} value).
2628 @end deffn
2629
2630 @deffn {Scheme Procedure} addrinfo:protocol ai
2631 Return the protocol of @var{ai}.
2632 @end deffn
2633
2634 @deffn {Scheme Procedure} addrinfo:addr ai
2635 Return the socket address associated with @var{ai} as a @code{sockaddr}
2636 object (@pxref{Network Socket Address}).
2637 @end deffn
2638
2639 @deffn {Scheme Procedure} addrinfo:canonname ai
2640 Return a string for the canonical name associated with @var{ai} if
2641 the @code{AI_CANONNAME} flag was supplied.
2642 @end deffn
2643
2644 @subsubheading The Host Database
2645 @cindex @file{/etc/hosts}
2646 @cindex network database
2647
2648 A @dfn{host object} is a structure that represents what is known about a
2649 network host, and is the usual way of representing a system's network
2650 identity inside software.
2651
2652 The following functions accept a host object and return a selected
2653 component:
2654
2655 @deffn {Scheme Procedure} hostent:name host
2656 The ``official'' hostname for @var{host}.
2657 @end deffn
2658 @deffn {Scheme Procedure} hostent:aliases host
2659 A list of aliases for @var{host}.
2660 @end deffn
2661 @deffn {Scheme Procedure} hostent:addrtype host
2662 The host address type, one of the @code{AF} constants, such as
2663 @code{AF_INET} or @code{AF_INET6}.
2664 @end deffn
2665 @deffn {Scheme Procedure} hostent:length host
2666 The length of each address for @var{host}, in bytes.
2667 @end deffn
2668 @deffn {Scheme Procedure} hostent:addr-list host
2669 The list of network addresses associated with @var{host}. For
2670 @code{AF_INET} these are integer IPv4 address (@pxref{Network Address
2671 Conversion}).
2672 @end deffn
2673
2674 The following procedures can be used to search the host database. However,
2675 @code{getaddrinfo} should be preferred over them since it's more generic and
2676 thread-safe.
2677
2678 @deffn {Scheme Procedure} gethost [host]
2679 @deffnx {Scheme Procedure} gethostbyname hostname
2680 @deffnx {Scheme Procedure} gethostbyaddr address
2681 @deffnx {C Function} scm_gethost (host)
2682 Look up a host by name or address, returning a host object. The
2683 @code{gethost} procedure will accept either a string name or an integer
2684 address; if given no arguments, it behaves like @code{gethostent} (see
2685 below). If a name or address is supplied but the address can not be
2686 found, an error will be thrown to one of the keys:
2687 @code{host-not-found}, @code{try-again}, @code{no-recovery} or
2688 @code{no-data}, corresponding to the equivalent @code{h_error} values.
2689 Unusual conditions may result in errors thrown to the
2690 @code{system-error} or @code{misc_error} keys.
2691
2692 @lisp
2693 (gethost "www.gnu.org")
2694 @result{} #("www.gnu.org" () 2 4 (3353880842))
2695
2696 (gethostbyname "www.emacs.org")
2697 @result{} #("emacs.org" ("www.emacs.org") 2 4 (1073448978))
2698 @end lisp
2699 @end deffn
2700
2701 The following procedures may be used to step through the host
2702 database from beginning to end.
2703
2704 @deffn {Scheme Procedure} sethostent [stayopen]
2705 Initialize an internal stream from which host objects may be read. This
2706 procedure must be called before any calls to @code{gethostent}, and may
2707 also be called afterward to reset the host entry stream. If
2708 @var{stayopen} is supplied and is not @code{#f}, the database is not
2709 closed by subsequent @code{gethostbyname} or @code{gethostbyaddr} calls,
2710 possibly giving an efficiency gain.
2711 @end deffn
2712
2713 @deffn {Scheme Procedure} gethostent
2714 Return the next host object from the host database, or @code{#f} if
2715 there are no more hosts to be found (or an error has been encountered).
2716 This procedure may not be used before @code{sethostent} has been called.
2717 @end deffn
2718
2719 @deffn {Scheme Procedure} endhostent
2720 Close the stream used by @code{gethostent}. The return value is unspecified.
2721 @end deffn
2722
2723 @deffn {Scheme Procedure} sethost [stayopen]
2724 @deffnx {C Function} scm_sethost (stayopen)
2725 If @var{stayopen} is omitted, this is equivalent to @code{endhostent}.
2726 Otherwise it is equivalent to @code{sethostent stayopen}.
2727 @end deffn
2728
2729 @subsubheading The Network Database
2730 @cindex network database
2731
2732 The following functions accept an object representing a network
2733 and return a selected component:
2734
2735 @deffn {Scheme Procedure} netent:name net
2736 The ``official'' network name.
2737 @end deffn
2738 @deffn {Scheme Procedure} netent:aliases net
2739 A list of aliases for the network.
2740 @end deffn
2741 @deffn {Scheme Procedure} netent:addrtype net
2742 The type of the network number. Currently, this returns only
2743 @code{AF_INET}.
2744 @end deffn
2745 @deffn {Scheme Procedure} netent:net net
2746 The network number.
2747 @end deffn
2748
2749 The following procedures are used to search the network database:
2750
2751 @deffn {Scheme Procedure} getnet [net]
2752 @deffnx {Scheme Procedure} getnetbyname net-name
2753 @deffnx {Scheme Procedure} getnetbyaddr net-number
2754 @deffnx {C Function} scm_getnet (net)
2755 Look up a network by name or net number in the network database. The
2756 @var{net-name} argument must be a string, and the @var{net-number}
2757 argument must be an integer. @code{getnet} will accept either type of
2758 argument, behaving like @code{getnetent} (see below) if no arguments are
2759 given.
2760 @end deffn
2761
2762 The following procedures may be used to step through the network
2763 database from beginning to end.
2764
2765 @deffn {Scheme Procedure} setnetent [stayopen]
2766 Initialize an internal stream from which network objects may be read. This
2767 procedure must be called before any calls to @code{getnetent}, and may
2768 also be called afterward to reset the net entry stream. If
2769 @var{stayopen} is supplied and is not @code{#f}, the database is not
2770 closed by subsequent @code{getnetbyname} or @code{getnetbyaddr} calls,
2771 possibly giving an efficiency gain.
2772 @end deffn
2773
2774 @deffn {Scheme Procedure} getnetent
2775 Return the next entry from the network database.
2776 @end deffn
2777
2778 @deffn {Scheme Procedure} endnetent
2779 Close the stream used by @code{getnetent}. The return value is unspecified.
2780 @end deffn
2781
2782 @deffn {Scheme Procedure} setnet [stayopen]
2783 @deffnx {C Function} scm_setnet (stayopen)
2784 If @var{stayopen} is omitted, this is equivalent to @code{endnetent}.
2785 Otherwise it is equivalent to @code{setnetent stayopen}.
2786 @end deffn
2787
2788 @subsubheading The Protocol Database
2789 @cindex @file{/etc/protocols}
2790 @cindex protocols
2791 @cindex network protocols
2792
2793 The following functions accept an object representing a protocol
2794 and return a selected component:
2795
2796 @deffn {Scheme Procedure} protoent:name protocol
2797 The ``official'' protocol name.
2798 @end deffn
2799 @deffn {Scheme Procedure} protoent:aliases protocol
2800 A list of aliases for the protocol.
2801 @end deffn
2802 @deffn {Scheme Procedure} protoent:proto protocol
2803 The protocol number.
2804 @end deffn
2805
2806 The following procedures are used to search the protocol database:
2807
2808 @deffn {Scheme Procedure} getproto [protocol]
2809 @deffnx {Scheme Procedure} getprotobyname name
2810 @deffnx {Scheme Procedure} getprotobynumber number
2811 @deffnx {C Function} scm_getproto (protocol)
2812 Look up a network protocol by name or by number. @code{getprotobyname}
2813 takes a string argument, and @code{getprotobynumber} takes an integer
2814 argument. @code{getproto} will accept either type, behaving like
2815 @code{getprotoent} (see below) if no arguments are supplied.
2816 @end deffn
2817
2818 The following procedures may be used to step through the protocol
2819 database from beginning to end.
2820
2821 @deffn {Scheme Procedure} setprotoent [stayopen]
2822 Initialize an internal stream from which protocol objects may be read. This
2823 procedure must be called before any calls to @code{getprotoent}, and may
2824 also be called afterward to reset the protocol entry stream. If
2825 @var{stayopen} is supplied and is not @code{#f}, the database is not
2826 closed by subsequent @code{getprotobyname} or @code{getprotobynumber} calls,
2827 possibly giving an efficiency gain.
2828 @end deffn
2829
2830 @deffn {Scheme Procedure} getprotoent
2831 Return the next entry from the protocol database.
2832 @end deffn
2833
2834 @deffn {Scheme Procedure} endprotoent
2835 Close the stream used by @code{getprotoent}. The return value is unspecified.
2836 @end deffn
2837
2838 @deffn {Scheme Procedure} setproto [stayopen]
2839 @deffnx {C Function} scm_setproto (stayopen)
2840 If @var{stayopen} is omitted, this is equivalent to @code{endprotoent}.
2841 Otherwise it is equivalent to @code{setprotoent stayopen}.
2842 @end deffn
2843
2844 @subsubheading The Service Database
2845 @cindex @file{/etc/services}
2846 @cindex services
2847 @cindex network services
2848
2849 The following functions accept an object representing a service
2850 and return a selected component:
2851
2852 @deffn {Scheme Procedure} servent:name serv
2853 The ``official'' name of the network service.
2854 @end deffn
2855 @deffn {Scheme Procedure} servent:aliases serv
2856 A list of aliases for the network service.
2857 @end deffn
2858 @deffn {Scheme Procedure} servent:port serv
2859 The Internet port used by the service.
2860 @end deffn
2861 @deffn {Scheme Procedure} servent:proto serv
2862 The protocol used by the service. A service may be listed many times
2863 in the database under different protocol names.
2864 @end deffn
2865
2866 The following procedures are used to search the service database:
2867
2868 @deffn {Scheme Procedure} getserv [name [protocol]]
2869 @deffnx {Scheme Procedure} getservbyname name protocol
2870 @deffnx {Scheme Procedure} getservbyport port protocol
2871 @deffnx {C Function} scm_getserv (name, protocol)
2872 Look up a network service by name or by service number, and return a
2873 network service object. The @var{protocol} argument specifies the name
2874 of the desired protocol; if the protocol found in the network service
2875 database does not match this name, a system error is signalled.
2876
2877 The @code{getserv} procedure will take either a service name or number
2878 as its first argument; if given no arguments, it behaves like
2879 @code{getservent} (see below).
2880
2881 @lisp
2882 (getserv "imap" "tcp")
2883 @result{} #("imap2" ("imap") 143 "tcp")
2884
2885 (getservbyport 88 "udp")
2886 @result{} #("kerberos" ("kerberos5" "krb5") 88 "udp")
2887 @end lisp
2888 @end deffn
2889
2890 The following procedures may be used to step through the service
2891 database from beginning to end.
2892
2893 @deffn {Scheme Procedure} setservent [stayopen]
2894 Initialize an internal stream from which service objects may be read. This
2895 procedure must be called before any calls to @code{getservent}, and may
2896 also be called afterward to reset the service entry stream. If
2897 @var{stayopen} is supplied and is not @code{#f}, the database is not
2898 closed by subsequent @code{getservbyname} or @code{getservbyport} calls,
2899 possibly giving an efficiency gain.
2900 @end deffn
2901
2902 @deffn {Scheme Procedure} getservent
2903 Return the next entry from the services database.
2904 @end deffn
2905
2906 @deffn {Scheme Procedure} endservent
2907 Close the stream used by @code{getservent}. The return value is unspecified.
2908 @end deffn
2909
2910 @deffn {Scheme Procedure} setserv [stayopen]
2911 @deffnx {C Function} scm_setserv (stayopen)
2912 If @var{stayopen} is omitted, this is equivalent to @code{endservent}.
2913 Otherwise it is equivalent to @code{setservent stayopen}.
2914 @end deffn
2915
2916
2917 @node Network Socket Address
2918 @subsubsection Network Socket Address
2919 @cindex socket address
2920 @cindex network socket address
2921 @tpindex Socket address
2922
2923 A @dfn{socket address} object identifies a socket endpoint for
2924 communication. In the case of @code{AF_INET} for instance, the socket
2925 address object comprises the host address (or interface on the host)
2926 and a port number which specifies a particular open socket in a
2927 running client or server process. A socket address object can be
2928 created with,
2929
2930 @deffn {Scheme Procedure} make-socket-address AF_INET ipv4addr port
2931 @deffnx {Scheme Procedure} make-socket-address AF_INET6 ipv6addr port [flowinfo [scopeid]]
2932 @deffnx {Scheme Procedure} make-socket-address AF_UNIX path
2933 @deffnx {C Function} scm_make_socket_address (family, address, arglist)
2934 Return a new socket address object. The first argument is the address
2935 family, one of the @code{AF} constants, then the arguments vary
2936 according to the family.
2937
2938 For @code{AF_INET} the arguments are an IPv4 network address number
2939 (@pxref{Network Address Conversion}), and a port number.
2940
2941 For @code{AF_INET6} the arguments are an IPv6 network address number
2942 and a port number. Optional @var{flowinfo} and @var{scopeid}
2943 arguments may be given (both integers, default 0).
2944
2945 For @code{AF_UNIX} the argument is a filename (a string).
2946
2947 The C function @code{scm_make_socket_address} takes the @var{family}
2948 and @var{address} arguments directly, then @var{arglist} is a list of
2949 further arguments, being the port for IPv4, port and optional flowinfo
2950 and scopeid for IPv6, or the empty list @code{SCM_EOL} for Unix
2951 domain.
2952 @end deffn
2953
2954 @noindent
2955 The following functions access the fields of a socket address object,
2956
2957 @deffn {Scheme Procedure} sockaddr:fam sa
2958 Return the address family from socket address object @var{sa}. This
2959 is one of the @code{AF} constants (e.g.@: @code{AF_INET}).
2960 @end deffn
2961
2962 @deffn {Scheme Procedure} sockaddr:path sa
2963 For an @code{AF_UNIX} socket address object @var{sa}, return the
2964 filename.
2965 @end deffn
2966
2967 @deffn {Scheme Procedure} sockaddr:addr sa
2968 For an @code{AF_INET} or @code{AF_INET6} socket address object
2969 @var{sa}, return the network address number.
2970 @end deffn
2971
2972 @deffn {Scheme Procedure} sockaddr:port sa
2973 For an @code{AF_INET} or @code{AF_INET6} socket address object
2974 @var{sa}, return the port number.
2975 @end deffn
2976
2977 @deffn {Scheme Procedure} sockaddr:flowinfo sa
2978 For an @code{AF_INET6} socket address object @var{sa}, return the
2979 flowinfo value.
2980 @end deffn
2981
2982 @deffn {Scheme Procedure} sockaddr:scopeid sa
2983 For an @code{AF_INET6} socket address object @var{sa}, return the
2984 scope ID value.
2985 @end deffn
2986
2987 @tpindex @code{struct sockaddr}
2988 @tpindex @code{sockaddr}
2989 The functions below convert to and from the C @code{struct sockaddr}
2990 (@pxref{Address Formats,,, libc, The GNU C Library Reference Manual}).
2991 That structure is a generic type, an application can cast to or from
2992 @code{struct sockaddr_in}, @code{struct sockaddr_in6} or @code{struct
2993 sockaddr_un} according to the address family.
2994
2995 In a @code{struct sockaddr} taken or returned, the byte ordering in
2996 the fields follows the C conventions (@pxref{Byte Order,, Byte Order
2997 Conversion, libc, The GNU C Library Reference Manual}). This means
2998 network byte order for @code{AF_INET} host address
2999 (@code{sin_addr.s_addr}) and port number (@code{sin_port}), and
3000 @code{AF_INET6} port number (@code{sin6_port}). But at the Scheme
3001 level these values are taken or returned in host byte order, so the
3002 port is an ordinary integer, and the host address likewise is an
3003 ordinary integer (as described in @ref{Network Address Conversion}).
3004
3005 @deftypefn {C Function} {struct sockaddr *} scm_c_make_socket_address (SCM family, SCM address, SCM args, size_t *outsize)
3006 Return a newly-@code{malloc}ed @code{struct sockaddr} created from
3007 arguments like those taken by @code{scm_make_socket_address} above.
3008
3009 The size (in bytes) of the @code{struct sockaddr} return is stored
3010 into @code{*@var{outsize}}. An application must call @code{free} to
3011 release the returned structure when no longer required.
3012 @end deftypefn
3013
3014 @deftypefn {C Function} SCM scm_from_sockaddr (const struct sockaddr *address, unsigned address_size)
3015 Return a Scheme socket address object from the C @var{address}
3016 structure. @var{address_size} is the size in bytes of @var{address}.
3017 @end deftypefn
3018
3019 @deftypefn {C Function} {struct sockaddr *} scm_to_sockaddr (SCM address, size_t *address_size)
3020 Return a newly-@code{malloc}ed @code{struct sockaddr} from a Scheme
3021 level socket address object.
3022
3023 The size (in bytes) of the @code{struct sockaddr} return is stored
3024 into @code{*@var{outsize}}. An application must call @code{free} to
3025 release the returned structure when no longer required.
3026 @end deftypefn
3027
3028
3029 @node Network Sockets and Communication
3030 @subsubsection Network Sockets and Communication
3031 @cindex socket
3032 @cindex network socket
3033
3034 Socket ports can be created using @code{socket} and @code{socketpair}.
3035 The ports are initially unbuffered, to make reading and writing to the
3036 same port more reliable. A buffer can be added to the port using
3037 @code{setvbuf}; see @ref{Ports and File Descriptors}.
3038
3039 Most systems have limits on how many files and sockets can be open, so
3040 it's strongly recommended that socket ports be closed explicitly when
3041 no longer required (@pxref{Ports}).
3042
3043 Some of the underlying C functions take values in network byte order,
3044 but the convention in Guile is that at the Scheme level everything is
3045 ordinary host byte order and conversions are made automatically where
3046 necessary.
3047
3048 @deffn {Scheme Procedure} socket family style proto
3049 @deffnx {C Function} scm_socket (family, style, proto)
3050 Return a new socket port of the type specified by @var{family},
3051 @var{style} and @var{proto}. All three parameters are integers. The
3052 possible values for @var{family} are as follows, where supported by
3053 the system,
3054
3055 @defvar PF_UNIX
3056 @defvarx PF_INET
3057 @defvarx PF_INET6
3058 @end defvar
3059
3060 The possible values for @var{style} are as follows, again where
3061 supported by the system,
3062
3063 @defvar SOCK_STREAM
3064 @defvarx SOCK_DGRAM
3065 @defvarx SOCK_RAW
3066 @defvarx SOCK_RDM
3067 @defvarx SOCK_SEQPACKET
3068 @end defvar
3069
3070 @var{proto} can be obtained from a protocol name using
3071 @code{getprotobyname} (@pxref{Network Databases}). A value of zero
3072 means the default protocol, which is usually right.
3073
3074 A socket cannot by used for communication until it has been connected
3075 somewhere, usually with either @code{connect} or @code{accept} below.
3076 @end deffn
3077
3078 @deffn {Scheme Procedure} socketpair family style proto
3079 @deffnx {C Function} scm_socketpair (family, style, proto)
3080 Return a pair, the @code{car} and @code{cdr} of which are two unnamed
3081 socket ports connected to each other. The connection is full-duplex,
3082 so data can be transferred in either direction between the two.
3083
3084 @var{family}, @var{style} and @var{proto} are as per @code{socket}
3085 above. But many systems only support socket pairs in the
3086 @code{PF_UNIX} family. Zero is likely to be the only meaningful value
3087 for @var{proto}.
3088 @end deffn
3089
3090 @deffn {Scheme Procedure} getsockopt sock level optname
3091 @deffnx {Scheme Procedure} setsockopt sock level optname value
3092 @deffnx {C Function} scm_getsockopt (sock, level, optname)
3093 @deffnx {C Function} scm_setsockopt (sock, level, optname, value)
3094 Get or set an option on socket port @var{sock}. @code{getsockopt}
3095 returns the current value. @code{setsockopt} sets a value and the
3096 return is unspecified.
3097
3098 @var{level} is an integer specifying a protocol layer, either
3099 @code{SOL_SOCKET} for socket level options, or a protocol number from
3100 the @code{IPPROTO} constants or @code{getprotoent} (@pxref{Network
3101 Databases}).
3102
3103 @defvar SOL_SOCKET
3104 @defvarx IPPROTO_IP
3105 @defvarx IPPROTO_TCP
3106 @defvarx IPPROTO_UDP
3107 @end defvar
3108
3109 @var{optname} is an integer specifying an option within the protocol
3110 layer.
3111
3112 For @code{SOL_SOCKET} level the following @var{optname}s are defined
3113 (when provided by the system). For their meaning see
3114 @ref{Socket-Level Options,,, libc, The GNU C Library Reference
3115 Manual}, or @command{man 7 socket}.
3116
3117 @defvar SO_DEBUG
3118 @defvarx SO_REUSEADDR
3119 @defvarx SO_STYLE
3120 @defvarx SO_TYPE
3121 @defvarx SO_ERROR
3122 @defvarx SO_DONTROUTE
3123 @defvarx SO_BROADCAST
3124 @defvarx SO_SNDBUF
3125 @defvarx SO_RCVBUF
3126 @defvarx SO_KEEPALIVE
3127 @defvarx SO_OOBINLINE
3128 @defvarx SO_NO_CHECK
3129 @defvarx SO_PRIORITY
3130 @defvarx SO_REUSEPORT
3131 The @var{value} taken or returned is an integer.
3132 @end defvar
3133
3134 @defvar SO_LINGER
3135 The @var{value} taken or returned is a pair of integers
3136 @code{(@var{ENABLE} . @var{TIMEOUT})}. On old systems without timeout
3137 support (ie.@: without @code{struct linger}), only @var{ENABLE} has an
3138 effect but the value in Guile is always a pair.
3139 @end defvar
3140
3141 @c Note that we refer only to ``man ip'' here. On GNU/Linux it's
3142 @c ``man 7 ip'' but on NetBSD it's ``man 4 ip''.
3143 @c
3144 For IP level (@code{IPPROTO_IP}) the following @var{optname}s are
3145 defined (when provided by the system). See @command{man ip} for what
3146 they mean.
3147
3148 @defvar IP_MULTICAST_IF
3149 This sets the source interface used by multicast traffic.
3150 @end defvar
3151
3152 @defvar IP_MULTICAST_TTL
3153 This sets the default TTL for multicast traffic. This defaults
3154 to 1 and should be increased to allow traffic to pass beyond the
3155 local network.
3156 @end defvar
3157
3158 @defvar IP_ADD_MEMBERSHIP
3159 @defvarx IP_DROP_MEMBERSHIP
3160 These can be used only with @code{setsockopt}, not @code{getsockopt}.
3161 @var{value} is a pair @code{(@var{MULTIADDR} . @var{INTERFACEADDR})}
3162 of integer IPv4 addresses (@pxref{Network Address Conversion}).
3163 @var{MULTIADDR} is a multicast address to be added to or dropped from
3164 the interface @var{INTERFACEADDR}. @var{INTERFACEADDR} can be
3165 @code{INADDR_ANY} to have the system select the interface.
3166 @var{INTERFACEADDR} can also be an interface index number, on systems
3167 supporting that.
3168 @end defvar
3169 @end deffn
3170
3171 @deffn {Scheme Procedure} shutdown sock how
3172 @deffnx {C Function} scm_shutdown (sock, how)
3173 Sockets can be closed simply by using @code{close-port}. The
3174 @code{shutdown} procedure allows reception or transmission on a
3175 connection to be shut down individually, according to the parameter
3176 @var{how}:
3177
3178 @table @asis
3179 @item 0
3180 Stop receiving data for this socket. If further data arrives, reject it.
3181 @item 1
3182 Stop trying to transmit data from this socket. Discard any
3183 data waiting to be sent. Stop looking for acknowledgement of
3184 data already sent; don't retransmit it if it is lost.
3185 @item 2
3186 Stop both reception and transmission.
3187 @end table
3188
3189 The return value is unspecified.
3190 @end deffn
3191
3192 @deffn {Scheme Procedure} connect sock sockaddr
3193 @deffnx {Scheme Procedure} connect sock AF_INET ipv4addr port
3194 @deffnx {Scheme Procedure} connect sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
3195 @deffnx {Scheme Procedure} connect sock AF_UNIX path
3196 @deffnx {C Function} scm_connect (sock, fam, address, args)
3197 Initiate a connection on socket port @var{sock} to a given address.
3198 The destination is either a socket address object, or arguments the
3199 same as @code{make-socket-address} would take to make such an object
3200 (@pxref{Network Socket Address}). The return value is unspecified.
3201
3202 @example
3203 (connect sock AF_INET INADDR_LOOPBACK 23)
3204 (connect sock (make-socket-address AF_INET INADDR_LOOPBACK 23))
3205 @end example
3206 @end deffn
3207
3208 @deffn {Scheme Procedure} bind sock sockaddr
3209 @deffnx {Scheme Procedure} bind sock AF_INET ipv4addr port
3210 @deffnx {Scheme Procedure} bind sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
3211 @deffnx {Scheme Procedure} bind sock AF_UNIX path
3212 @deffnx {C Function} scm_bind (sock, fam, address, args)
3213 Bind socket port @var{sock} to the given address. The address is
3214 either a socket address object, or arguments the same as
3215 @code{make-socket-address} would take to make such an object
3216 (@pxref{Network Socket Address}). The return value is unspecified.
3217
3218 Generally a socket is only explicitly bound to a particular address
3219 when making a server, i.e.@: to listen on a particular port. For an
3220 outgoing connection the system will assign a local address
3221 automatically, if not already bound.
3222
3223 @example
3224 (bind sock AF_INET INADDR_ANY 12345)
3225 (bind sock (make-socket-address AF_INET INADDR_ANY 12345))
3226 @end example
3227 @end deffn
3228
3229 @deffn {Scheme Procedure} listen sock backlog
3230 @deffnx {C Function} scm_listen (sock, backlog)
3231 Enable @var{sock} to accept connection
3232 requests. @var{backlog} is an integer specifying
3233 the maximum length of the queue for pending connections.
3234 If the queue fills, new clients will fail to connect until
3235 the server calls @code{accept} to accept a connection from
3236 the queue.
3237
3238 The return value is unspecified.
3239 @end deffn
3240
3241 @deffn {Scheme Procedure} accept sock
3242 @deffnx {C Function} scm_accept (sock)
3243 Accept a connection from socket port @var{sock} which has been enabled
3244 for listening with @code{listen} above. If there are no incoming
3245 connections in the queue, wait until one is available (unless
3246 @code{O_NONBLOCK} has been set on the socket, @pxref{Ports and File
3247 Descriptors,@code{fcntl}}).
3248
3249 The return value is a pair. The @code{car} is a new socket port,
3250 connected and ready to communicate. The @code{cdr} is a socket
3251 address object (@pxref{Network Socket Address}) which is where the
3252 remote connection is from (like @code{getpeername} below).
3253
3254 All communication takes place using the new socket returned. The
3255 given @var{sock} remains bound and listening, and @code{accept} may be
3256 called on it again to get another incoming connection when desired.
3257 @end deffn
3258
3259 @deffn {Scheme Procedure} getsockname sock
3260 @deffnx {C Function} scm_getsockname (sock)
3261 Return a socket address object which is the where @var{sock} is bound
3262 locally. @var{sock} may have obtained its local address from
3263 @code{bind} (above), or if a @code{connect} is done with an otherwise
3264 unbound socket (which is usual) then the system will have assigned an
3265 address.
3266
3267 Note that on many systems the address of a socket in the
3268 @code{AF_UNIX} namespace cannot be read.
3269 @end deffn
3270
3271 @deffn {Scheme Procedure} getpeername sock
3272 @deffnx {C Function} scm_getpeername (sock)
3273 Return a socket address object which is where @var{sock} is connected
3274 to, i.e.@: the remote endpoint.
3275
3276 Note that on many systems the address of a socket in the
3277 @code{AF_UNIX} namespace cannot be read.
3278 @end deffn
3279
3280 @deffn {Scheme Procedure} recv! sock buf [flags]
3281 @deffnx {C Function} scm_recv (sock, buf, flags)
3282 Receive data from a socket port.
3283 @var{sock} must already
3284 be bound to the address from which data is to be received.
3285 @var{buf} is a bytevector into which
3286 the data will be written. The size of @var{buf} limits
3287 the amount of
3288 data which can be received: in the case of packet
3289 protocols, if a packet larger than this limit is encountered
3290 then some data
3291 will be irrevocably lost.
3292
3293 @vindex MSG_OOB
3294 @vindex MSG_PEEK
3295 @vindex MSG_DONTROUTE
3296 The optional @var{flags} argument is a value or bitwise OR of
3297 @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3298
3299 The value returned is the number of bytes read from the
3300 socket.
3301
3302 Note that the data is read directly from the socket file
3303 descriptor:
3304 any unread buffered port data is ignored.
3305 @end deffn
3306
3307 @deffn {Scheme Procedure} send sock message [flags]
3308 @deffnx {C Function} scm_send (sock, message, flags)
3309 @vindex MSG_OOB
3310 @vindex MSG_PEEK
3311 @vindex MSG_DONTROUTE
3312 Transmit bytevector @var{message} on socket port @var{sock}.
3313 @var{sock} must already be bound to a destination address. The value
3314 returned is the number of bytes transmitted---it's possible for this
3315 to be less than the length of @var{message} if the socket is set to be
3316 non-blocking. The optional @var{flags} argument is a value or bitwise
3317 OR of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3318
3319 Note that the data is written directly to the socket
3320 file descriptor:
3321 any unflushed buffered port data is ignored.
3322 @end deffn
3323
3324 @deffn {Scheme Procedure} recvfrom! sock buf [flags [start [end]]]
3325 @deffnx {C Function} scm_recvfrom (sock, buf, flags, start, end)
3326 Receive data from socket port @var{sock}, returning the originating
3327 address as well as the data. This function is usually for datagram
3328 sockets, but can be used on stream-oriented sockets too.
3329
3330 The data received is stored in bytevector @var{buf}, using
3331 either the whole bytevector or just the region between the optional
3332 @var{start} and @var{end} positions. The size of @var{buf}
3333 limits the amount of data that can be received. For datagram
3334 protocols if a packet larger than this is received then excess
3335 bytes are irrevocably lost.
3336
3337 The return value is a pair. The @code{car} is the number of bytes
3338 read. The @code{cdr} is a socket address object (@pxref{Network
3339 Socket Address}) which is where the data came from, or @code{#f} if
3340 the origin is unknown.
3341
3342 @vindex MSG_OOB
3343 @vindex MSG_PEEK
3344 @vindex MSG_DONTROUTE
3345 The optional @var{flags} argument is a or bitwise-OR (@code{logior})
3346 of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3347
3348 Data is read directly from the socket file descriptor, any buffered
3349 port data is ignored.
3350
3351 @c This was linux kernel 2.6.15 and glibc 2.3.6, not sure what any
3352 @c specs are supposed to say about recvfrom threading.
3353 @c
3354 On a GNU/Linux system @code{recvfrom!} is not multi-threading, all
3355 threads stop while a @code{recvfrom!} call is in progress. An
3356 application may need to use @code{select}, @code{O_NONBLOCK} or
3357 @code{MSG_DONTWAIT} to avoid this.
3358 @end deffn
3359
3360 @deffn {Scheme Procedure} sendto sock message sockaddr [flags]
3361 @deffnx {Scheme Procedure} sendto sock message AF_INET ipv4addr port [flags]
3362 @deffnx {Scheme Procedure} sendto sock message AF_INET6 ipv6addr port [flowinfo [scopeid [flags]]]
3363 @deffnx {Scheme Procedure} sendto sock message AF_UNIX path [flags]
3364 @deffnx {C Function} scm_sendto (sock, message, fam, address, args_and_flags)
3365 Transmit bytevector @var{message} as a datagram socket port
3366 @var{sock}. The destination is specified either as a socket address
3367 object, or as arguments the same as would be taken by
3368 @code{make-socket-address} to create such an object (@pxref{Network
3369 Socket Address}).
3370
3371 The destination address may be followed by an optional @var{flags}
3372 argument which is a @code{logior} (@pxref{Bitwise Operations}) of
3373 @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3374
3375 The value returned is the number of bytes transmitted --
3376 it's possible for
3377 this to be less than the length of @var{message} if the
3378 socket is
3379 set to be non-blocking.
3380 Note that the data is written directly to the socket
3381 file descriptor:
3382 any unflushed buffered port data is ignored.
3383 @end deffn
3384
3385 The following functions can be used to convert short and long integers
3386 between ``host'' and ``network'' order. Although the procedures above do
3387 this automatically for addresses, the conversion will still need to
3388 be done when sending or receiving encoded integer data from the network.
3389
3390 @deffn {Scheme Procedure} htons value
3391 @deffnx {C Function} scm_htons (value)
3392 Convert a 16 bit quantity from host to network byte ordering.
3393 @var{value} is packed into 2 bytes, which are then converted
3394 and returned as a new integer.
3395 @end deffn
3396
3397 @deffn {Scheme Procedure} ntohs value
3398 @deffnx {C Function} scm_ntohs (value)
3399 Convert a 16 bit quantity from network to host byte ordering.
3400 @var{value} is packed into 2 bytes, which are then converted
3401 and returned as a new integer.
3402 @end deffn
3403
3404 @deffn {Scheme Procedure} htonl value
3405 @deffnx {C Function} scm_htonl (value)
3406 Convert a 32 bit quantity from host to network byte ordering.
3407 @var{value} is packed into 4 bytes, which are then converted
3408 and returned as a new integer.
3409 @end deffn
3410
3411 @deffn {Scheme Procedure} ntohl value
3412 @deffnx {C Function} scm_ntohl (value)
3413 Convert a 32 bit quantity from network to host byte ordering.
3414 @var{value} is packed into 4 bytes, which are then converted
3415 and returned as a new integer.
3416 @end deffn
3417
3418 These procedures are inconvenient to use at present, but consider:
3419
3420 @example
3421 (define write-network-long
3422 (lambda (value port)
3423 (let ((v (make-uniform-vector 1 1 0)))
3424 (uniform-vector-set! v 0 (htonl value))
3425 (uniform-vector-write v port))))
3426
3427 (define read-network-long
3428 (lambda (port)
3429 (let ((v (make-uniform-vector 1 1 0)))
3430 (uniform-vector-read! v port)
3431 (ntohl (uniform-vector-ref v 0)))))
3432 @end example
3433
3434
3435 @node Internet Socket Examples
3436 @subsubsection Network Socket Examples
3437 @cindex network examples
3438 @cindex socket examples
3439
3440 The following give examples of how to use network sockets.
3441
3442 @subsubheading Internet Socket Client Example
3443
3444 @cindex socket client example
3445 The following example demonstrates an Internet socket client.
3446 It connects to the HTTP daemon running on the local machine and
3447 returns the contents of the root index URL.
3448
3449 @example
3450 (let ((s (socket PF_INET SOCK_STREAM 0)))
3451 (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 80)
3452 (display "GET / HTTP/1.0\r\n\r\n" s)
3453
3454 (do ((line (read-line s) (read-line s)))
3455 ((eof-object? line))
3456 (display line)
3457 (newline)))
3458 @end example
3459
3460
3461 @subsubheading Internet Socket Server Example
3462
3463 @cindex socket server example
3464 The following example shows a simple Internet server which listens on
3465 port 2904 for incoming connections and sends a greeting back to the
3466 client.
3467
3468 @example
3469 (let ((s (socket PF_INET SOCK_STREAM 0)))
3470 (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
3471 ;; @r{Specific address?}
3472 ;; @r{(bind s AF_INET (inet-pton AF_INET "127.0.0.1") 2904)}
3473 (bind s AF_INET INADDR_ANY 2904)
3474 (listen s 5)
3475
3476 (simple-format #t "Listening for clients in pid: ~S" (getpid))
3477 (newline)
3478
3479 (while #t
3480 (let* ((client-connection (accept s))
3481 (client-details (cdr client-connection))
3482 (client (car client-connection)))
3483 (simple-format #t "Got new client connection: ~S"
3484 client-details)
3485 (newline)
3486 (simple-format #t "Client address: ~S"
3487 (gethostbyaddr
3488 (sockaddr:addr client-details)))
3489 (newline)
3490 ;; @r{Send back the greeting to the client port}
3491 (display "Hello client\r\n" client)
3492 (close client))))
3493 @end example
3494
3495
3496 @node System Identification
3497 @subsection System Identification
3498 @cindex system name
3499
3500 This section lists the various procedures Guile provides for accessing
3501 information about the system it runs on.
3502
3503 @deffn {Scheme Procedure} uname
3504 @deffnx {C Function} scm_uname ()
3505 Return an object with some information about the computer
3506 system the program is running on.
3507
3508 The following procedures accept an object as returned by @code{uname}
3509 and return a selected component (all of which are strings).
3510
3511 @deffn {Scheme Procedure} utsname:sysname un
3512 The name of the operating system.
3513 @end deffn
3514 @deffn {Scheme Procedure} utsname:nodename un
3515 The network name of the computer.
3516 @end deffn
3517 @deffn {Scheme Procedure} utsname:release un
3518 The current release level of the operating system implementation.
3519 @end deffn
3520 @deffn {Scheme Procedure} utsname:version un
3521 The current version level within the release of the operating system.
3522 @end deffn
3523 @deffn {Scheme Procedure} utsname:machine un
3524 A description of the hardware.
3525 @end deffn
3526 @end deffn
3527
3528 @deffn {Scheme Procedure} gethostname
3529 @deffnx {C Function} scm_gethostname ()
3530 @cindex host name
3531 Return the host name of the current processor.
3532 @end deffn
3533
3534 @deffn {Scheme Procedure} sethostname name
3535 @deffnx {C Function} scm_sethostname (name)
3536 Set the host name of the current processor to @var{name}. May
3537 only be used by the superuser. The return value is not
3538 specified.
3539 @end deffn
3540
3541 @node Locales
3542 @subsection Locales
3543 @cindex locale
3544
3545 @deffn {Scheme Procedure} setlocale category [locale]
3546 @deffnx {C Function} scm_setlocale (category, locale)
3547 Get or set the current locale, used for various internationalizations.
3548 Locales are strings, such as @samp{sv_SE}.
3549
3550 If @var{locale} is given then the locale for the given @var{category}
3551 is set and the new value returned. If @var{locale} is not given then
3552 the current value is returned. @var{category} should be one of the
3553 following values (@pxref{Locale Categories, Categories of Activities
3554 that Locales Affect,, libc, The GNU C Library Reference Manual}):
3555
3556 @defvar LC_ALL
3557 @defvarx LC_COLLATE
3558 @defvarx LC_CTYPE
3559 @defvarx LC_MESSAGES
3560 @defvarx LC_MONETARY
3561 @defvarx LC_NUMERIC
3562 @defvarx LC_TIME
3563 @end defvar
3564
3565 @cindex @code{LANG}
3566 A common usage is @samp{(setlocale LC_ALL "")}, which initializes all
3567 categories based on standard environment variables (@code{LANG} etc).
3568 For full details on categories and locale names @pxref{Locales,,
3569 Locales and Internationalization, libc, The GNU C Library Reference
3570 Manual}.
3571
3572 Note that @code{setlocale} affects locale settings for the whole
3573 process. @xref{i18n Introduction, locale objects and
3574 @code{make-locale}}, for a thread-safe alternative.
3575 @end deffn
3576
3577 @node Encryption
3578 @subsection Encryption
3579 @cindex encryption
3580
3581 Please note that the procedures in this section are not suited for
3582 strong encryption, they are only interfaces to the well-known and
3583 common system library functions of the same name. They are just as good
3584 (or bad) as the underlying functions, so you should refer to your system
3585 documentation before using them (@pxref{crypt,, Encrypting Passwords,
3586 libc, The GNU C Library Reference Manual}).
3587
3588 @deffn {Scheme Procedure} crypt key salt
3589 @deffnx {C Function} scm_crypt (key, salt)
3590 Encrypt @var{key}, with the addition of @var{salt} (both strings),
3591 using the @code{crypt} C library call.
3592 @end deffn
3593
3594 Although @code{getpass} is not an encryption procedure per se, it
3595 appears here because it is often used in combination with @code{crypt}:
3596
3597 @deffn {Scheme Procedure} getpass prompt
3598 @deffnx {C Function} scm_getpass (prompt)
3599 @cindex password
3600 Display @var{prompt} to the standard error output and read
3601 a password from @file{/dev/tty}. If this file is not
3602 accessible, it reads from standard input. The password may be
3603 up to 127 characters in length. Additional characters and the
3604 terminating newline character are discarded. While reading
3605 the password, echoing and the generation of signals by special
3606 characters is disabled.
3607 @end deffn
3608
3609
3610 @c Local Variables:
3611 @c TeX-master: "guile.texi"
3612 @c End: