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.
8 @section @acronym{POSIX} System Calls and Networking
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.
30 @subsection @acronym{POSIX} Interface Conventions
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)}).
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}.
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.
47 General naming conventions are as follows:
51 The Scheme name is often identical to the name of the underlying Unix
54 Underscores in Unix procedure names are converted to hyphens.
56 Procedures which destructively modify Scheme data have exclamation
57 marks appended, e.g., @code{recv!}.
59 Predicates (returning only @code{#t} or @code{#f}) have question marks
60 appended, e.g., @code{access?}.
62 Some names are changed to avoid conflict with dissimilar interfaces
63 defined by scsh, e.g., @code{primitive-fork}.
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
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
76 For ways to deal with exceptions, see @ref{Exceptions}.
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,
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))
93 (lambda () (dup2 -123 -456))
105 @defun system-error-errno arglist
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,
115 (mkdir "/this-ought-to-fail-if-I'm-not-root"))
117 (let ((errno (system-error-errno stuff)))
120 (display "You're not allowed to do that."))
122 (display "Already exists."))
124 (display (strerror errno))))
130 @node Ports and File Descriptors
131 @subsection Ports and File Descriptors
132 @cindex file descriptor
134 Conventions generally follow those of scsh, @ref{The Scheme shell (scsh)}.
136 File ports are implemented using low-level operating system I/O
137 facilities, with optional buffering to improve efficiency; see
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}.
145 The @code{force-output} and @code{drain-input} procedures can be used
146 to clear the buffers.
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
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.
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.
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.
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}.
184 @deffn {Scheme Procedure} port-revealed port
185 @deffnx {C Function} scm_port_revealed (port)
186 Return the revealed count for @var{port}.
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.
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.
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.
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}).
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
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.
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.
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.
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.
251 @deffn {Scheme Procedure} release-port-handle port
252 Decrements the revealed count for a port.
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.
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).
271 @var{flags} can be constructed by combining variables using @code{logior}.
275 Open the file read-only.
278 Open the file write-only.
281 Open the file read/write.
284 Append to the file instead of truncating.
287 Create the file if it does not already exist.
290 @xref{File Status Flags,,,libc,The GNU C Library Reference Manual},
291 for additional flags.
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
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.
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.
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
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.
333 @deffn {Scheme Procedure} pipe
334 @deffnx {C Function} scm_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}.
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}).
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.
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.
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.
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.
373 @deffn {Scheme Procedure} dup->inport port/fd [newfd]
374 Returns a new input port using the new file descriptor.
377 @deffn {Scheme Procedure} dup->outport port/fd [newfd]
378 Returns a new output port using the new file descriptor.
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.
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}).
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.
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
402 This procedure is equivalent to @code{(dup->port @var{port} @var{modes})}.
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.
413 The return value is unspecified.
415 Unexpected behaviour can result if both ports are subsequently used
416 and the original and/or duplicate ports are buffered.
418 This procedure does not have any side effects on other ports or
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
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.
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.
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.
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}
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:
470 block buffered, using a newly allocated buffer of @var{size} bytes.
471 If @var{size} is omitted, a default size will be used.
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.
481 Values for @var{cmd} are:
484 Duplicate the file descriptor, the same as @code{dup->fdes} above
490 Get or set flags associated with the file descriptor. The only flag
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
499 (fcntl port F_SETFD FD_CLOEXEC)
502 Or better, set it but leave any other possible future flags unchanged,
505 (fcntl port F_SETFD (logior FD_CLOEXEC
506 (fcntl port F_GETFD)))
513 Get or set flags associated with the open file. These flags are
514 @code{O_RDONLY} etc described under @code{open} above.
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.
520 (fcntl sock F_SETFL (logior O_NONBLOCK
521 (fcntl sock F_GETFL)))
527 Get or set the process ID of a socket's owner, for @code{SIGIO} signals.
531 @deffn {Scheme Procedure} flock file operation
532 @deffnx {C Function} scm_flock (file, operation)
534 Apply or remove an advisory lock on an open file.
535 @var{operation} specifies the action to be done:
538 Shared lock. More than one process may hold a shared lock
539 for a given file at a given time.
542 Exclusive lock. Only one process may hold an exclusive lock
543 for a given file at a given time.
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}).
555 The return value is not specified. @var{file} may be an open
556 file descriptor or an open file descriptor port.
558 Note that @code{flock} does not lock files across NFS.
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.
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.
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.
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.
595 @subsection File System
598 These procedures allow querying and setting file system attributes
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.
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
611 @var{how} is an integer which is one of the following values, or a
612 bitwise-OR (@code{logior}) of multiple values.
615 Test for read permission.
618 Test for write permission.
621 Test for execute permission.
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.
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.
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
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}.
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
656 The object returned by @code{stat} can be passed as a single
657 parameter to the following procedures, all of which return
660 @deffn {Scheme Procedure} stat:dev st
661 The device number containing the file.
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.
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.
672 @deffn {Scheme Procedure} stat:nlink st
673 The number of hard links to the file.
675 @deffn {Scheme Procedure} stat:uid st
676 The user ID of the file's owner.
678 @deffn {Scheme Procedure} stat:gid st
679 The group ID of the file.
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}.
686 @deffn {Scheme Procedure} stat:size st
687 The size of a regular file in bytes.
689 @deffn {Scheme Procedure} stat:atime st
690 The last access time for the file, in seconds.
692 @deffn {Scheme Procedure} stat:mtime st
693 The last modification time for the file, in seconds.
695 @deffn {Scheme Procedure} stat:ctime st
696 The last modification time for the attributes of the file, in seconds.
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.
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.
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}.
717 In addition, the following procedures return the information
718 from @code{stat:mode} in a more convenient form:
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},
726 @deffn {Scheme Procedure} stat:perms st
727 An integer representing the access permission bits.
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.
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.
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.
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.
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).
770 the new permissions as a decimal number, e.g., @code{(chmod "foo" #o755)}.
771 The return value is unspecified.
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.
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
787 (utime "foo" (- (current-time) 3600))
789 will set the access time to one hour in the past and the
790 modification time to the current time.
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
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.
807 @deffn {Scheme Procedure} rename-file oldname newname
808 @deffnx {C Function} scm_rename (oldname, newname)
809 Renames the file specified by @var{oldname} to @var{newname}.
810 The return value is unspecified.
813 @deffn {Scheme Procedure} link oldpath newpath
814 @deffnx {C Function} scm_link (oldpath, newpath)
815 Creates a new name @var{newpath} in the file system for the
816 file named by @var{oldpath}. If @var{oldpath} is a symbolic
817 link, the link may or may not be followed depending on the
821 @deffn {Scheme Procedure} symlink oldpath newpath
822 @deffnx {C Function} scm_symlink (oldpath, newpath)
823 Create a symbolic link named @var{newpath} with the value (i.e., pointing to)
824 @var{oldpath}. The return value is unspecified.
827 @deffn {Scheme Procedure} mkdir path [mode]
828 @deffnx {C Function} scm_mkdir (path, mode)
829 Create a new directory named by @var{path}. If @var{mode} is omitted
830 then the permissions of the directory file are set using the current
831 umask (@pxref{Processes}). Otherwise they are set to the decimal
832 value specified with @var{mode}. The return value is unspecified.
835 @deffn {Scheme Procedure} rmdir path
836 @deffnx {C Function} scm_rmdir (path)
837 Remove the existing directory named by @var{path}. The directory must
838 be empty for this to succeed. The return value is unspecified.
841 @deffn {Scheme Procedure} opendir dirname
842 @deffnx {C Function} scm_opendir (dirname)
843 @cindex directory contents
844 Open the directory specified by @var{dirname} and return a directory
847 Before using this and the procedures below, make sure to see the
848 higher-level procedures for directory traversal that are available
849 (@pxref{File Tree Walk}).
852 @deffn {Scheme Procedure} directory-stream? object
853 @deffnx {C Function} scm_directory_stream_p (object)
854 Return a boolean indicating whether @var{object} is a directory
855 stream as returned by @code{opendir}.
858 @deffn {Scheme Procedure} readdir stream
859 @deffnx {C Function} scm_readdir (stream)
860 Return (as a string) the next directory entry from the directory stream
861 @var{stream}. If there is no remaining entry to be read then the
862 end of file object is returned.
865 @deffn {Scheme Procedure} rewinddir stream
866 @deffnx {C Function} scm_rewinddir (stream)
867 Reset the directory port @var{stream} so that the next call to
868 @code{readdir} will return the first directory entry.
871 @deffn {Scheme Procedure} closedir stream
872 @deffnx {C Function} scm_closedir (stream)
873 Close the directory stream @var{stream}.
874 The return value is unspecified.
877 Here is an example showing how to display all the entries in a
881 (define dir (opendir "/usr/lib"))
882 (do ((entry (readdir dir) (readdir dir)))
883 ((eof-object? entry))
884 (display entry)(newline))
888 @deffn {Scheme Procedure} sync
889 @deffnx {C Function} scm_sync ()
890 Flush the operating system disk buffers.
891 The return value is unspecified.
894 @deffn {Scheme Procedure} mknod path type perms dev
895 @deffnx {C Function} scm_mknod (path, type, perms, dev)
897 Creates a new special file, such as a file corresponding to a device.
898 @var{path} specifies the name of the file. @var{type} should be one
899 of the following symbols: @samp{regular}, @samp{directory},
900 @samp{symlink}, @samp{block-special}, @samp{char-special},
901 @samp{fifo}, or @samp{socket}. @var{perms} (an integer) specifies the
902 file permissions. @var{dev} (an integer) specifies which device the
903 special file refers to. Its exact interpretation depends on the kind
904 of special file being created.
908 (mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))
911 The return value is unspecified.
914 @deffn {Scheme Procedure} tmpnam
915 @deffnx {C Function} scm_tmpnam ()
916 @cindex temporary file
917 Return an auto-generated name of a temporary file, a file which
918 doesn't already exist. The name includes a path, it's usually in
919 @file{/tmp} but that's system dependent.
921 Care must be taken when using @code{tmpnam}. In between choosing the
922 name and creating the file another program might use that name, or an
923 attacker might even make it a symlink pointing at something important
924 and causing you to overwrite that.
926 The safe way is to create the file using @code{open} with
927 @code{O_EXCL} to avoid any overwriting. A loop can try again with
928 another name if the file exists (error @code{EEXIST}).
929 @code{mkstemp!} below does that.
932 @deffn {Scheme Procedure} mkstemp! tmpl
933 @deffnx {C Function} scm_mkstemp (tmpl)
934 @cindex temporary file
935 Create a new unique file in the file system and return a new buffered
936 port open for reading and writing to the file.
938 @var{tmpl} is a string specifying where the file should be created: it
939 must end with @samp{XXXXXX} and those @samp{X}s will be changed in the
940 string to return the name of the file. (@code{port-filename} on the
941 port also gives the name.)
943 POSIX doesn't specify the permissions mode of the file, on GNU and
944 most systems it's @code{#o600}. An application can use @code{chmod}
945 to relax that if desired. For example @code{#o666} less @code{umask},
946 which is usual for ordinary file creation,
949 (let ((port (mkstemp! (string-copy "/tmp/myfile-XXXXXX"))))
950 (chmod port (logand #o666 (lognot (umask))))
955 @deffn {Scheme Procedure} tmpfile
956 @deffnx {C Function} scm_tmpfile ()
957 Return an input/output port to a unique temporary file
958 named using the path prefix @code{P_tmpdir} defined in
960 The file is automatically deleted when the port is closed
961 or the program terminates.
964 @deffn {Scheme Procedure} dirname filename
965 @deffnx {C Function} scm_dirname (filename)
966 Return the directory name component of the file name
967 @var{filename}. If @var{filename} does not contain a directory
968 component, @code{.} is returned.
971 @deffn {Scheme Procedure} basename filename [suffix]
972 @deffnx {C Function} scm_basename (filename, suffix)
973 Return the base name of the file name @var{filename}. The
974 base name is the file name without any directory components.
975 If @var{suffix} is provided, and is equal to the end of
976 @var{basename}, it is removed also.
979 (basename "/tmp/test.xml" ".xml")
984 @deffn {Scheme Procedure} file-exists? filename
985 Return @code{#t} if the file named @var{filename} exists, @code{#f} if
990 @node User Information
991 @subsection User Information
992 @cindex user information
993 @cindex password file
996 The facilities in this section provide an interface to the user and
998 They should be used with care since they are not reentrant.
1000 The following functions accept an object representing user information
1001 and return a selected component:
1003 @deffn {Scheme Procedure} passwd:name pw
1004 The name of the userid.
1006 @deffn {Scheme Procedure} passwd:passwd pw
1007 The encrypted passwd.
1009 @deffn {Scheme Procedure} passwd:uid pw
1012 @deffn {Scheme Procedure} passwd:gid pw
1013 The group id number.
1015 @deffn {Scheme Procedure} passwd:gecos pw
1018 @deffn {Scheme Procedure} passwd:dir pw
1021 @deffn {Scheme Procedure} passwd:shell pw
1026 @deffn {Scheme Procedure} getpwuid uid
1027 Look up an integer userid in the user database.
1030 @deffn {Scheme Procedure} getpwnam name
1031 Look up a user name string in the user database.
1034 @deffn {Scheme Procedure} setpwent
1035 Initializes a stream used by @code{getpwent} to read from the user database.
1036 The next use of @code{getpwent} will return the first entry. The
1037 return value is unspecified.
1040 @deffn {Scheme Procedure} getpwent
1041 Read the next entry in the user database stream. The return is a
1042 passwd user object as above, or @code{#f} when no more entries.
1045 @deffn {Scheme Procedure} endpwent
1046 Closes the stream used by @code{getpwent}. The return value is unspecified.
1049 @deffn {Scheme Procedure} setpw [arg]
1050 @deffnx {C Function} scm_setpwent (arg)
1051 If called with a true argument, initialize or reset the password data
1052 stream. Otherwise, close the stream. The @code{setpwent} and
1053 @code{endpwent} procedures are implemented on top of this.
1056 @deffn {Scheme Procedure} getpw [user]
1057 @deffnx {C Function} scm_getpwuid (user)
1058 Look up an entry in the user database. @var{user} can be an integer,
1059 a string, or omitted, giving the behaviour of getpwuid, getpwnam
1060 or getpwent respectively.
1063 The following functions accept an object representing group information
1064 and return a selected component:
1066 @deffn {Scheme Procedure} group:name gr
1069 @deffn {Scheme Procedure} group:passwd gr
1070 The encrypted group password.
1072 @deffn {Scheme Procedure} group:gid gr
1073 The group id number.
1075 @deffn {Scheme Procedure} group:mem gr
1076 A list of userids which have this group as a supplementary group.
1080 @deffn {Scheme Procedure} getgrgid gid
1081 Look up an integer group id in the group database.
1084 @deffn {Scheme Procedure} getgrnam name
1085 Look up a group name in the group database.
1088 @deffn {Scheme Procedure} setgrent
1089 Initializes a stream used by @code{getgrent} to read from the group database.
1090 The next use of @code{getgrent} will return the first entry.
1091 The return value is unspecified.
1094 @deffn {Scheme Procedure} getgrent
1095 Return the next entry in the group database, using the stream set by
1099 @deffn {Scheme Procedure} endgrent
1100 Closes the stream used by @code{getgrent}.
1101 The return value is unspecified.
1104 @deffn {Scheme Procedure} setgr [arg]
1105 @deffnx {C Function} scm_setgrent (arg)
1106 If called with a true argument, initialize or reset the group data
1107 stream. Otherwise, close the stream. The @code{setgrent} and
1108 @code{endgrent} procedures are implemented on top of this.
1111 @deffn {Scheme Procedure} getgr [group]
1112 @deffnx {C Function} scm_getgrgid (group)
1113 Look up an entry in the group database. @var{group} can be an integer,
1114 a string, or omitted, giving the behaviour of getgrgid, getgrnam
1115 or getgrent respectively.
1118 In addition to the accessor procedures for the user database, the
1119 following shortcut procedure is also available.
1121 @deffn {Scheme Procedure} getlogin
1122 @deffnx {C Function} scm_getlogin ()
1123 Return a string containing the name of the user logged in on
1124 the controlling terminal of the process, or @code{#f} if this
1125 information cannot be obtained.
1133 @deffn {Scheme Procedure} current-time
1134 @deffnx {C Function} scm_current_time ()
1135 Return the number of seconds since 1970-01-01 00:00:00 @acronym{UTC},
1136 excluding leap seconds.
1139 @deffn {Scheme Procedure} gettimeofday
1140 @deffnx {C Function} scm_gettimeofday ()
1141 Return a pair containing the number of seconds and microseconds
1142 since 1970-01-01 00:00:00 @acronym{UTC}, excluding leap seconds. Note:
1143 whether true microsecond resolution is available depends on the
1147 The following procedures either accept an object representing a broken down
1148 time and return a selected component, or accept an object representing
1149 a broken down time and a value and set the component to the value.
1150 The numbers in parentheses give the usual range.
1152 @deffn {Scheme Procedure} tm:sec tm
1153 @deffnx {Scheme Procedure} set-tm:sec tm val
1156 @deffn {Scheme Procedure} tm:min tm
1157 @deffnx {Scheme Procedure} set-tm:min tm val
1160 @deffn {Scheme Procedure} tm:hour tm
1161 @deffnx {Scheme Procedure} set-tm:hour tm val
1164 @deffn {Scheme Procedure} tm:mday tm
1165 @deffnx {Scheme Procedure} set-tm:mday tm val
1166 Day of the month (1-31).
1168 @deffn {Scheme Procedure} tm:mon tm
1169 @deffnx {Scheme Procedure} set-tm:mon tm val
1172 @deffn {Scheme Procedure} tm:year tm
1173 @deffnx {Scheme Procedure} set-tm:year tm val
1174 Year (70-), the year minus 1900.
1176 @deffn {Scheme Procedure} tm:wday tm
1177 @deffnx {Scheme Procedure} set-tm:wday tm val
1178 Day of the week (0-6) with Sunday represented as 0.
1180 @deffn {Scheme Procedure} tm:yday tm
1181 @deffnx {Scheme Procedure} set-tm:yday tm val
1182 Day of the year (0-364, 365 in leap years).
1184 @deffn {Scheme Procedure} tm:isdst tm
1185 @deffnx {Scheme Procedure} set-tm:isdst tm val
1186 Daylight saving indicator (0 for ``no'', greater than 0 for ``yes'', less than
1189 @deffn {Scheme Procedure} tm:gmtoff tm
1190 @deffnx {Scheme Procedure} set-tm:gmtoff tm val
1191 Time zone offset in seconds west of @acronym{UTC} (-46800 to 43200).
1192 For example on East coast USA (zone @samp{EST+5}) this would be 18000
1193 (ie.@: @m{5\times60\times60,5*60*60}) in winter, or 14400
1194 (ie.@: @m{4\times60\times60,4*60*60}) during daylight savings.
1196 Note @code{tm:gmtoff} is not the same as @code{tm_gmtoff} in the C
1197 @code{tm} structure. @code{tm_gmtoff} is seconds east and hence the
1198 negative of the value here.
1200 @deffn {Scheme Procedure} tm:zone tm
1201 @deffnx {Scheme Procedure} set-tm:zone tm val
1202 Time zone label (a string), not necessarily unique.
1206 @deffn {Scheme Procedure} localtime time [zone]
1207 @deffnx {C Function} scm_localtime (time, zone)
1209 Return an object representing the broken down components of
1210 @var{time}, an integer like the one returned by
1211 @code{current-time}. The time zone for the calculation is
1212 optionally specified by @var{zone} (a string), otherwise the
1213 @env{TZ} environment variable or the system default is used.
1216 @deffn {Scheme Procedure} gmtime time
1217 @deffnx {C Function} scm_gmtime (time)
1218 Return an object representing the broken down components of
1219 @var{time}, an integer like the one returned by
1220 @code{current-time}. The values are calculated for @acronym{UTC}.
1223 @deffn {Scheme Procedure} mktime sbd-time [zone]
1224 @deffnx {C Function} scm_mktime (sbd_time, zone)
1225 For a broken down time object @var{sbd-time}, return a pair the
1226 @code{car} of which is an integer time like @code{current-time}, and
1227 the @code{cdr} of which is a new broken down time with normalized
1230 @var{zone} is a timezone string, or the default is the @env{TZ}
1231 environment variable or the system default (@pxref{TZ Variable,,
1232 Specifying the Time Zone with @env{TZ}, libc, GNU C Library Reference
1233 Manual}). @var{sbd-time} is taken to be in that @var{zone}.
1235 The following fields of @var{sbd-time} are used: @code{tm:year},
1236 @code{tm:mon}, @code{tm:mday}, @code{tm:hour}, @code{tm:min},
1237 @code{tm:sec}, @code{tm:isdst}. The values can be outside their usual
1238 ranges. For example @code{tm:hour} normally goes up to 23, but a
1239 value say 33 would mean 9 the following day.
1241 @code{tm:isdst} in @var{sbd-time} says whether the time given is with
1242 daylight savings or not. This is ignored if @var{zone} doesn't have
1243 any daylight savings adjustment amount.
1245 The broken down time in the return normalizes the values of
1246 @var{sbd-time} by bringing them into their usual ranges, and using the
1247 actual daylight savings rule for that time in @var{zone} (which may
1248 differ from what @var{sbd-time} had). The easiest way to think of
1249 this is that @var{sbd-time} plus @var{zone} converts to the integer
1250 UTC time, then a @code{localtime} is applied to get the normal
1251 presentation of that time, in @var{zone}.
1254 @deffn {Scheme Procedure} tzset
1255 @deffnx {C Function} scm_tzset ()
1256 Initialize the timezone from the @env{TZ} environment variable
1257 or the system default. It's not usually necessary to call this procedure
1258 since it's done automatically by other procedures that depend on the
1262 @deffn {Scheme Procedure} strftime format tm
1263 @deffnx {C Function} scm_strftime (format, tm)
1264 @cindex time formatting
1265 Return a string which is broken-down time structure @var{tm} formatted
1266 according to the given @var{format} string.
1268 @var{format} contains field specifications introduced by a @samp{%}
1269 character. See @ref{Formatting Calendar Time,,, libc, The GNU C
1270 Library Reference Manual}, or @samp{man 3 strftime}, for the available
1274 (strftime "%c" (localtime (current-time)))
1275 @result{} "Mon Mar 11 20:17:43 2002"
1278 If @code{setlocale} has been called (@pxref{Locales}), month and day
1279 names are from the current locale and in the locale character set.
1282 @deffn {Scheme Procedure} strptime format string
1283 @deffnx {C Function} scm_strptime (format, string)
1284 @cindex time parsing
1285 Performs the reverse action to @code{strftime}, parsing
1286 @var{string} according to the specification supplied in
1287 @var{format}. The interpretation of month and day names is
1288 dependent on the current locale. The value returned is a pair.
1289 The @acronym{CAR} has an object with time components
1290 in the form returned by @code{localtime} or @code{gmtime},
1291 but the time zone components
1292 are not usefully set.
1293 The @acronym{CDR} reports the number of characters from @var{string}
1294 which were used for the conversion.
1297 @defvar internal-time-units-per-second
1298 The value of this variable is the number of time units per second
1299 reported by the following procedures.
1302 @deffn {Scheme Procedure} times
1303 @deffnx {C Function} scm_times ()
1304 Return an object with information about real and processor
1305 time. The following procedures accept such an object as an
1306 argument and return a selected component:
1308 @deffn {Scheme Procedure} tms:clock tms
1309 The current real time, expressed as time units relative to an
1312 @deffn {Scheme Procedure} tms:utime tms
1313 The CPU time units used by the calling process.
1315 @deffn {Scheme Procedure} tms:stime tms
1316 The CPU time units used by the system on behalf of the calling
1319 @deffn {Scheme Procedure} tms:cutime tms
1320 The CPU time units used by terminated child processes of the
1321 calling process, whose status has been collected (e.g., using
1324 @deffn {Scheme Procedure} tms:cstime tms
1325 Similarly, the CPU times units used by the system on behalf of
1326 terminated child processes.
1330 @deffn {Scheme Procedure} get-internal-real-time
1331 @deffnx {C Function} scm_get_internal_real_time ()
1332 Return the number of time units since the interpreter was
1336 @deffn {Scheme Procedure} get-internal-run-time
1337 @deffnx {C Function} scm_get_internal_run_time ()
1338 Return the number of time units of processor time used by the
1339 interpreter. Both @emph{system} and @emph{user} time are
1340 included but subprocesses are not.
1343 @node Runtime Environment
1344 @subsection Runtime Environment
1346 @deffn {Scheme Procedure} program-arguments
1347 @deffnx {Scheme Procedure} command-line
1348 @deffnx {Scheme Procedure} set-program-arguments
1349 @deffnx {C Function} scm_program_arguments ()
1350 @deffnx {C Function} scm_set_program_arguments_scm (lst)
1351 @cindex command line
1352 @cindex program arguments
1353 Get the command line arguments passed to Guile, or set new arguments.
1355 The arguments are a list of strings, the first of which is the invoked
1356 program name. This is just @nicode{"guile"} (or the executable path)
1357 when run interactively, or it's the script name when running a script
1358 with @option{-s} (@pxref{Invoking Guile}).
1361 guile -L /my/extra/dir -s foo.scm abc def
1363 (program-arguments) @result{} ("foo.scm" "abc" "def")
1366 @code{set-program-arguments} allows a library module or similar to
1367 modify the arguments, for example to strip options it recognises,
1368 leaving the rest for the mainline.
1370 The argument list is held in a fluid, which means it's separate for
1371 each thread. Neither the list nor the strings within it are copied at
1372 any point and normally should not be mutated.
1374 The two names @code{program-arguments} and @code{command-line} are an
1375 historical accident, they both do exactly the same thing. The name
1376 @code{scm_set_program_arguments_scm} has an extra @code{_scm} on the
1377 end to avoid clashing with the C function below.
1380 @deftypefn {C Function} void scm_set_program_arguments (int argc, char **argv, char *first)
1381 @cindex command line
1382 @cindex program arguments
1383 Set the list of command line arguments for @code{program-arguments}
1384 and @code{command-line} above.
1386 @var{argv} is an array of null-terminated strings, as in a C
1387 @code{main} function. @var{argc} is the number of strings in
1388 @var{argv}, or if it's negative then a @code{NULL} in @var{argv} marks
1391 @var{first} is an extra string put at the start of the arguments, or
1392 @code{NULL} for no such extra. This is a convenient way to pass the
1393 program name after advancing @var{argv} to strip option arguments.
1398 char *progname = argv[0];
1399 for (argv++; argv[0] != NULL && argv[0][0] == '-'; argv++)
1401 /* munch option ... */
1403 /* remaining args for scheme level use */
1404 scm_set_program_arguments (-1, argv, progname);
1408 This sort of thing is often done at startup under
1409 @code{scm_boot_guile} with options handled at the C level removed.
1410 The given strings are all copied, so the C data is not accessed again
1411 once @code{scm_set_program_arguments} returns.
1414 @deffn {Scheme Procedure} getenv name
1415 @deffnx {C Function} scm_getenv (name)
1417 Looks up the string @var{name} in the current environment. The return
1418 value is @code{#f} unless a string of the form @code{NAME=VALUE} is
1419 found, in which case the string @code{VALUE} is returned.
1422 @deffn {Scheme Procedure} setenv name value
1423 Modifies the environment of the current process, which is
1424 also the default environment inherited by child processes.
1426 If @var{value} is @code{#f}, then @var{name} is removed from the
1427 environment. Otherwise, the string @var{name}=@var{value} is added
1428 to the environment, replacing any existing string with name matching
1431 The return value is unspecified.
1434 @deffn {Scheme Procedure} unsetenv name
1435 Remove variable @var{name} from the environment. The
1436 name can not contain a @samp{=} character.
1439 @deffn {Scheme Procedure} environ [env]
1440 @deffnx {C Function} scm_environ (env)
1441 If @var{env} is omitted, return the current environment (in the
1442 Unix sense) as a list of strings. Otherwise set the current
1443 environment, which is also the default environment for child
1444 processes, to the supplied list of strings. Each member of
1445 @var{env} should be of the form @var{name}=@var{value} and values of
1446 @var{name} should not be duplicated. If @var{env} is supplied
1447 then the return value is unspecified.
1450 @deffn {Scheme Procedure} putenv str
1451 @deffnx {C Function} scm_putenv (str)
1452 Modifies the environment of the current process, which is
1453 also the default environment inherited by child processes.
1455 If @var{str} is of the form @code{NAME=VALUE} then it will be written
1456 directly into the environment, replacing any existing environment string
1458 name matching @code{NAME}. If @var{str} does not contain an equal
1459 sign, then any existing string with name matching @var{str} will
1462 The return value is unspecified.
1467 @subsection Processes
1469 @cindex child processes
1472 @deffn {Scheme Procedure} chdir str
1473 @deffnx {C Function} scm_chdir (str)
1474 @cindex current directory
1475 Change the current working directory to @var{str}.
1476 The return value is unspecified.
1480 @deffn {Scheme Procedure} getcwd
1481 @deffnx {C Function} scm_getcwd ()
1482 Return the name of the current working directory.
1485 @deffn {Scheme Procedure} umask [mode]
1486 @deffnx {C Function} scm_umask (mode)
1487 If @var{mode} is omitted, returns a decimal number representing the
1488 current file creation mask. Otherwise the file creation mask is set
1489 to @var{mode} and the previous value is returned. @xref{Setting
1490 Permissions,,Assigning File Permissions,libc,The GNU C Library
1491 Reference Manual}, for more on how to use umasks.
1493 E.g., @code{(umask #o022)} sets the mask to octal 22/decimal 18.
1496 @deffn {Scheme Procedure} chroot path
1497 @deffnx {C Function} scm_chroot (path)
1498 Change the root directory to that specified in @var{path}.
1499 This directory will be used for path names beginning with
1500 @file{/}. The root directory is inherited by all children
1501 of the current process. Only the superuser may change the
1505 @deffn {Scheme Procedure} getpid
1506 @deffnx {C Function} scm_getpid ()
1507 Return an integer representing the current process ID.
1510 @deffn {Scheme Procedure} getgroups
1511 @deffnx {C Function} scm_getgroups ()
1512 Return a vector of integers representing the current
1513 supplementary group IDs.
1516 @deffn {Scheme Procedure} getppid
1517 @deffnx {C Function} scm_getppid ()
1518 Return an integer representing the process ID of the parent
1522 @deffn {Scheme Procedure} getuid
1523 @deffnx {C Function} scm_getuid ()
1524 Return an integer representing the current real user ID.
1527 @deffn {Scheme Procedure} getgid
1528 @deffnx {C Function} scm_getgid ()
1529 Return an integer representing the current real group ID.
1532 @deffn {Scheme Procedure} geteuid
1533 @deffnx {C Function} scm_geteuid ()
1534 Return an integer representing the current effective user ID.
1535 If the system does not support effective IDs, then the real ID
1536 is returned. @code{(provided? 'EIDs)} reports whether the
1537 system supports effective IDs.
1540 @deffn {Scheme Procedure} getegid
1541 @deffnx {C Function} scm_getegid ()
1542 Return an integer representing the current effective group ID.
1543 If the system does not support effective IDs, then the real ID
1544 is returned. @code{(provided? 'EIDs)} reports whether the
1545 system supports effective IDs.
1548 @deffn {Scheme Procedure} setgroups vec
1549 @deffnx {C Function} scm_setgroups (vec)
1550 Set the current set of supplementary group IDs to the integers in the
1551 given vector @var{vec}. The return value is unspecified.
1553 Generally only the superuser can set the process group IDs
1554 (@pxref{Setting Groups, Setting the Group IDs,, libc, The GNU C
1555 Library Reference Manual}).
1558 @deffn {Scheme Procedure} setuid id
1559 @deffnx {C Function} scm_setuid (id)
1560 Sets both the real and effective user IDs to the integer @var{id}, provided
1561 the process has appropriate privileges.
1562 The return value is unspecified.
1565 @deffn {Scheme Procedure} setgid id
1566 @deffnx {C Function} scm_setgid (id)
1567 Sets both the real and effective group IDs to the integer @var{id}, provided
1568 the process has appropriate privileges.
1569 The return value is unspecified.
1572 @deffn {Scheme Procedure} seteuid id
1573 @deffnx {C Function} scm_seteuid (id)
1574 Sets the effective user ID to the integer @var{id}, provided the process
1575 has appropriate privileges. If effective IDs are not supported, the
1576 real ID is set instead---@code{(provided? 'EIDs)} reports whether the
1577 system supports effective IDs.
1578 The return value is unspecified.
1581 @deffn {Scheme Procedure} setegid id
1582 @deffnx {C Function} scm_setegid (id)
1583 Sets the effective group ID to the integer @var{id}, provided the process
1584 has appropriate privileges. If effective IDs are not supported, the
1585 real ID is set instead---@code{(provided? 'EIDs)} reports whether the
1586 system supports effective IDs.
1587 The return value is unspecified.
1590 @deffn {Scheme Procedure} getpgrp
1591 @deffnx {C Function} scm_getpgrp ()
1592 Return an integer representing the current process group ID.
1593 This is the @acronym{POSIX} definition, not @acronym{BSD}.
1596 @deffn {Scheme Procedure} setpgid pid pgid
1597 @deffnx {C Function} scm_setpgid (pid, pgid)
1598 Move the process @var{pid} into the process group @var{pgid}. @var{pid} or
1599 @var{pgid} must be integers: they can be zero to indicate the ID of the
1601 Fails on systems that do not support job control.
1602 The return value is unspecified.
1605 @deffn {Scheme Procedure} setsid
1606 @deffnx {C Function} scm_setsid ()
1607 Creates a new session. The current process becomes the session leader
1608 and is put in a new process group. The process will be detached
1609 from its controlling terminal if it has one.
1610 The return value is an integer representing the new process group ID.
1613 @deffn {Scheme Procedure} getsid pid
1614 @deffnx {C Function} scm_getsid (pid)
1615 Returns the session ID of process @var{pid}. (The session
1616 ID of a process is the process group ID of its session leader.)
1619 @deffn {Scheme Procedure} waitpid pid [options]
1620 @deffnx {C Function} scm_waitpid (pid, options)
1621 This procedure collects status information from a child process which
1622 has terminated or (optionally) stopped. Normally it will
1623 suspend the calling process until this can be done. If more than one
1624 child process is eligible then one will be chosen by the operating system.
1626 The value of @var{pid} determines the behaviour:
1629 @item @var{pid} greater than 0
1630 Request status information from the specified child process.
1631 @item @var{pid} equal to -1 or @code{WAIT_ANY}
1633 Request status information for any child process.
1634 @item @var{pid} equal to 0 or @code{WAIT_MYPGRP}
1636 Request status information for any child process in the current process
1638 @item @var{pid} less than -1
1639 Request status information for any child process whose process group ID
1640 is @minus{}@var{pid}.
1643 The @var{options} argument, if supplied, should be the bitwise OR of the
1644 values of zero or more of the following variables:
1647 Return immediately even if there are no child processes to be collected.
1651 Report status information for stopped processes as well as terminated
1655 The return value is a pair containing:
1659 The process ID of the child process, or 0 if @code{WNOHANG} was
1660 specified and no process was collected.
1662 The integer status value.
1667 functions can be used to decode the process status code returned
1670 @deffn {Scheme Procedure} status:exit-val status
1671 @deffnx {C Function} scm_status_exit_val (status)
1672 Return the exit status value, as would be set if a process
1673 ended normally through a call to @code{exit} or @code{_exit},
1674 if any, otherwise @code{#f}.
1677 @deffn {Scheme Procedure} status:term-sig status
1678 @deffnx {C Function} scm_status_term_sig (status)
1679 Return the signal number which terminated the process, if any,
1680 otherwise @code{#f}.
1683 @deffn {Scheme Procedure} status:stop-sig status
1684 @deffnx {C Function} scm_status_stop_sig (status)
1685 Return the signal number which stopped the process, if any,
1686 otherwise @code{#f}.
1689 @deffn {Scheme Procedure} system [cmd]
1690 @deffnx {C Function} scm_system (cmd)
1691 Execute @var{cmd} using the operating system's ``command
1692 processor''. Under Unix this is usually the default shell
1693 @code{sh}. The value returned is @var{cmd}'s exit status as
1694 returned by @code{waitpid}, which can be interpreted using the
1697 If @code{system} is called without arguments, return a boolean
1698 indicating whether the command processor is available.
1701 @deffn {Scheme Procedure} system* arg1 arg2 @dots{}
1702 @deffnx {C Function} scm_system_star (args)
1703 Execute the command indicated by @var{arg1} @var{arg2} @enddots{}. The
1704 first element must be a string indicating the command to be executed,
1705 and the remaining items must be strings representing each of the
1706 arguments to that command.
1708 This function returns the exit status of the command as provided by
1709 @code{waitpid}. This value can be handled with @code{status:exit-val}
1710 and the related functions.
1712 @code{system*} is similar to @code{system}, but accepts only one
1713 string per-argument, and performs no shell interpretation. The
1714 command is executed using fork and execlp. Accordingly this function
1715 may be safer than @code{system} in situations where shell
1716 interpretation is not required.
1718 Example: (system* "echo" "foo" "bar")
1721 @deffn {Scheme Procedure} primitive-exit [status]
1722 @deffnx {Scheme Procedure} primitive-_exit [status]
1723 @deffnx {C Function} scm_primitive_exit (status)
1724 @deffnx {C Function} scm_primitive__exit (status)
1725 Terminate the current process without unwinding the Scheme stack. The
1726 exit status is @var{status} if supplied, otherwise zero.
1728 @code{primitive-exit} uses the C @code{exit} function and hence runs
1729 usual C level cleanups (flush output streams, call @code{atexit}
1730 functions, etc, see @ref{Normal Termination,,, libc, The GNU C Library
1731 Reference Manual})).
1733 @code{primitive-_exit} is the @code{_exit} system call
1734 (@pxref{Termination Internals,,, libc, The GNU C Library Reference
1735 Manual}). This terminates the program immediately, with neither
1736 Scheme-level nor C-level cleanups.
1738 The typical use for @code{primitive-_exit} is from a child process
1739 created with @code{primitive-fork}. For example in a Gdk program the
1740 child process inherits the X server connection and a C-level
1741 @code{atexit} cleanup which will close that connection. But closing
1742 in the child would upset the protocol in the parent, so
1743 @code{primitive-_exit} should be used to exit without that.
1746 @deffn {Scheme Procedure} execl filename arg @dots{}
1747 @deffnx {C Function} scm_execl (filename, args)
1748 Executes the file named by @var{filename} as a new process image.
1749 The remaining arguments are supplied to the process; from a C program
1750 they are accessible as the @code{argv} argument to @code{main}.
1751 Conventionally the first @var{arg} is the same as @var{filename}.
1752 All arguments must be strings.
1754 If @var{arg} is missing, @var{filename} is executed with a null
1755 argument list, which may have system-dependent side-effects.
1757 This procedure is currently implemented using the @code{execv} system
1758 call, but we call it @code{execl} because of its Scheme calling interface.
1761 @deffn {Scheme Procedure} execlp filename arg @dots{}
1762 @deffnx {C Function} scm_execlp (filename, args)
1763 Similar to @code{execl}, however if
1764 @var{filename} does not contain a slash
1765 then the file to execute will be located by searching the
1766 directories listed in the @code{PATH} environment variable.
1768 This procedure is currently implemented using the @code{execvp} system
1769 call, but we call it @code{execlp} because of its Scheme calling interface.
1772 @deffn {Scheme Procedure} execle filename env arg @dots{}
1773 @deffnx {C Function} scm_execle (filename, env, args)
1774 Similar to @code{execl}, but the environment of the new process is
1775 specified by @var{env}, which must be a list of strings as returned by the
1776 @code{environ} procedure.
1778 This procedure is currently implemented using the @code{execve} system
1779 call, but we call it @code{execle} because of its Scheme calling interface.
1782 @deffn {Scheme Procedure} primitive-fork
1783 @deffnx {C Function} scm_fork ()
1784 Creates a new ``child'' process by duplicating the current ``parent'' process.
1785 In the child the return value is 0. In the parent the return value is
1786 the integer process ID of the child.
1788 Note that it is unsafe to fork a process that has multiple threads
1789 running, as only the thread that calls @code{primitive-fork} will
1790 persist in the child. Any resources that other threads held, such as
1791 locked mutexes or open file descriptors, are lost. Indeed, @acronym{POSIX}
1792 specifies that only async-signal-safe procedures are safe to call after
1793 a multithreaded fork, which is a very limited set. Guile issues a
1794 warning if it detects a fork from a multi-threaded program.
1796 If you are going to @code{exec} soon after forking, the procedures in
1797 @code{(ice-9 popen)} may be useful to you, as they fork and exec within
1798 an async-signal-safe function carefully written to ensure robust program
1799 behavior, even in the presence of threads. @xref{Pipes}, for more.
1801 This procedure has been renamed from @code{fork} to avoid a naming conflict
1805 @deffn {Scheme Procedure} nice incr
1806 @deffnx {C Function} scm_nice (incr)
1807 @cindex process priority
1808 Increment the priority of the current process by @var{incr}. A higher
1809 priority value means that the process runs less often.
1810 The return value is unspecified.
1813 @deffn {Scheme Procedure} setpriority which who prio
1814 @deffnx {C Function} scm_setpriority (which, who, prio)
1815 @vindex PRIO_PROCESS
1818 Set the scheduling priority of the process, process group
1819 or user, as indicated by @var{which} and @var{who}. @var{which}
1820 is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
1821 or @code{PRIO_USER}, and @var{who} is interpreted relative to
1822 @var{which} (a process identifier for @code{PRIO_PROCESS},
1823 process group identifier for @code{PRIO_PGRP}, and a user
1824 identifier for @code{PRIO_USER}. A zero value of @var{who}
1825 denotes the current process, process group, or user.
1826 @var{prio} is a value in the range [@minus{}20,20]. The default
1827 priority is 0; lower priorities (in numerical terms) cause more
1828 favorable scheduling. Sets the priority of all of the specified
1829 processes. Only the super-user may lower priorities. The return
1830 value is not specified.
1833 @deffn {Scheme Procedure} getpriority which who
1834 @deffnx {C Function} scm_getpriority (which, who)
1835 @vindex PRIO_PROCESS
1838 Return the scheduling priority of the process, process group
1839 or user, as indicated by @var{which} and @var{who}. @var{which}
1840 is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
1841 or @code{PRIO_USER}, and @var{who} should be interpreted depending on
1842 @var{which} (a process identifier for @code{PRIO_PROCESS},
1843 process group identifier for @code{PRIO_PGRP}, and a user
1844 identifier for @code{PRIO_USER}). A zero value of @var{who}
1845 denotes the current process, process group, or user. Return
1846 the highest priority (lowest numerical value) of any of the
1847 specified processes.
1850 @cindex affinity, CPU
1852 @deffn {Scheme Procedure} getaffinity pid
1853 @deffnx {C Function} scm_getaffinity (pid)
1854 Return a bitvector representing the CPU affinity mask for
1855 process @var{pid}. Each CPU the process has affinity with
1856 has its corresponding bit set in the returned bitvector.
1857 The number of bits set is a good estimate of how many CPUs
1858 Guile can use without stepping on other processes' toes.
1860 Currently this procedure is only defined on GNU variants
1861 (@pxref{CPU Affinity, @code{sched_getaffinity},, libc, The
1862 GNU C Library Reference Manual}).
1865 @deffn {Scheme Procedure} setaffinity pid mask
1866 @deffnx {C Function} scm_setaffinity (pid, mask)
1867 Install the CPU affinity mask @var{mask}, a bitvector, for
1868 the process or thread with ID @var{pid}. The return value
1871 Currently this procedure is only defined on GNU variants
1872 (@pxref{CPU Affinity, @code{sched_setaffinity},, libc, The
1873 GNU C Library Reference Manual}).
1876 @deffn {Scheme Procedure} total-processor-count
1877 @deffnx {C Function} scm_total_processor_count ()
1878 Return the total number of processors of the machine, which
1879 is guaranteed to be at least 1. A ``processor'' here is a
1880 thread execution unit, which can be either:
1883 @item an execution core in a (possibly multi-core) chip, in a
1884 (possibly multi- chip) module, in a single computer, or
1885 @item a thread execution unit inside a core in the case of
1886 @dfn{hyper-threaded} CPUs.
1889 Which of the two definitions is used, is unspecified.
1892 @deffn {Scheme Procedure} current-processor-count
1893 @deffnx {C Function} scm_current_processor_count ()
1894 Like @code{total-processor-count}, but return the number of
1895 processors available to the current process. See
1896 @code{setaffinity} and @code{getaffinity} for more
1905 The following procedures raise, handle and wait for signals.
1907 Scheme code signal handlers are run via a system async (@pxref{System
1908 asyncs}), so they're called in the handler's thread at the next safe
1909 opportunity. Generally this is after any currently executing
1910 primitive procedure finishes (which could be a long time for
1911 primitives that wait for an external event).
1913 @deffn {Scheme Procedure} kill pid sig
1914 @deffnx {C Function} scm_kill (pid, sig)
1915 Sends a signal to the specified process or group of processes.
1917 @var{pid} specifies the processes to which the signal is sent:
1920 @item @var{pid} greater than 0
1921 The process whose identifier is @var{pid}.
1922 @item @var{pid} equal to 0
1923 All processes in the current process group.
1924 @item @var{pid} less than -1
1925 The process group whose identifier is -@var{pid}
1926 @item @var{pid} equal to -1
1927 If the process is privileged, all processes except for some special
1928 system processes. Otherwise, all processes with the current effective
1932 @var{sig} should be specified using a variable corresponding to
1933 the Unix symbolic name, e.g.,
1943 A full list of signals on the GNU system may be found in @ref{Standard
1944 Signals,,,libc,The GNU C Library Reference Manual}.
1947 @deffn {Scheme Procedure} raise sig
1948 @deffnx {C Function} scm_raise (sig)
1949 Sends a specified signal @var{sig} to the current process, where
1950 @var{sig} is as described for the @code{kill} procedure.
1953 @deffn {Scheme Procedure} sigaction signum [handler [flags [thread]]]
1954 @deffnx {C Function} scm_sigaction (signum, handler, flags)
1955 @deffnx {C Function} scm_sigaction_for_thread (signum, handler, flags, thread)
1956 Install or report the signal handler for a specified signal.
1958 @var{signum} is the signal number, which can be specified using the value
1959 of variables such as @code{SIGINT}.
1961 If @var{handler} is omitted, @code{sigaction} returns a pair: the
1962 @acronym{CAR} is the current signal hander, which will be either an
1963 integer with the value @code{SIG_DFL} (default action) or
1964 @code{SIG_IGN} (ignore), or the Scheme procedure which handles the
1965 signal, or @code{#f} if a non-Scheme procedure handles the signal.
1966 The @acronym{CDR} contains the current @code{sigaction} flags for the
1969 If @var{handler} is provided, it is installed as the new handler for
1970 @var{signum}. @var{handler} can be a Scheme procedure taking one
1971 argument, or the value of @code{SIG_DFL} (default action) or
1972 @code{SIG_IGN} (ignore), or @code{#f} to restore whatever signal handler
1973 was installed before @code{sigaction} was first used. When a scheme
1974 procedure has been specified, that procedure will run in the given
1975 @var{thread}. When no thread has been given, the thread that made this
1976 call to @code{sigaction} is used.
1978 @var{flags} is a @code{logior} (@pxref{Bitwise Operations}) of the
1979 following (where provided by the system), or @code{0} for none.
1981 @defvar SA_NOCLDSTOP
1982 By default, @code{SIGCHLD} is signalled when a child process stops
1983 (ie.@: receives @code{SIGSTOP}), and when a child process terminates.
1984 With the @code{SA_NOCLDSTOP} flag, @code{SIGCHLD} is only signalled
1985 for termination, not stopping.
1987 @code{SA_NOCLDSTOP} has no effect on signals other than
1992 If a signal occurs while in a system call, deliver the signal then
1993 restart the system call (as opposed to returning an @code{EINTR} error
1997 The return value is a pair with information about the old handler as
2000 This interface does not provide access to the ``signal blocking''
2001 facility. Maybe this is not needed, since the thread support may
2002 provide solutions to the problem of consistent access to data
2006 @deffn {Scheme Procedure} restore-signals
2007 @deffnx {C Function} scm_restore_signals ()
2008 Return all signal handlers to the values they had before any call to
2009 @code{sigaction} was made. The return value is unspecified.
2012 @deffn {Scheme Procedure} alarm i
2013 @deffnx {C Function} scm_alarm (i)
2014 Set a timer to raise a @code{SIGALRM} signal after the specified
2015 number of seconds (an integer). It's advisable to install a signal
2017 @code{SIGALRM} beforehand, since the default action is to terminate
2020 The return value indicates the time remaining for the previous alarm,
2021 if any. The new value replaces the previous alarm. If there was
2022 no previous alarm, the return value is zero.
2025 @deffn {Scheme Procedure} pause
2026 @deffnx {C Function} scm_pause ()
2027 Pause the current process (thread?) until a signal arrives whose
2028 action is to either terminate the current process or invoke a
2029 handler procedure. The return value is unspecified.
2032 @deffn {Scheme Procedure} sleep secs
2033 @deffnx {Scheme Procedure} usleep usecs
2034 @deffnx {C Function} scm_sleep (secs)
2035 @deffnx {C Function} scm_usleep (usecs)
2036 Wait the given period @var{secs} seconds or @var{usecs} microseconds
2037 (both integers). If a signal arrives the wait stops and the return
2038 value is the time remaining, in seconds or microseconds respectively.
2039 If the period elapses with no signal the return is zero.
2041 On most systems the process scheduler is not microsecond accurate and
2042 the actual period slept by @code{usleep} might be rounded to a system
2043 clock tick boundary, which might be 10 milliseconds for instance.
2045 See @code{scm_std_sleep} and @code{scm_std_usleep} for equivalents at
2046 the C level (@pxref{Blocking}).
2049 @deffn {Scheme Procedure} getitimer which_timer
2050 @deffnx {Scheme Procedure} setitimer which_timer interval_seconds interval_microseconds periodic_seconds periodic_microseconds
2051 @deffnx {C Function} scm_getitimer (which_timer)
2052 @deffnx {C Function} scm_setitimer (which_timer, interval_seconds, interval_microseconds, periodic_seconds, periodic_microseconds)
2053 Get or set the periods programmed in certain system timers. These
2054 timers have a current interval value which counts down and on reaching
2055 zero raises a signal. An optional periodic value can be set to
2056 restart from there each time, for periodic operation.
2057 @var{which_timer} is one of the following values
2060 A real-time timer, counting down elapsed real time. At zero it raises
2061 @code{SIGALRM}. This is like @code{alarm} above, but with a higher
2065 @defvar ITIMER_VIRTUAL
2066 A virtual-time timer, counting down while the current process is
2067 actually using CPU. At zero it raises @code{SIGVTALRM}.
2071 A profiling timer, counting down while the process is running (like
2072 @code{ITIMER_VIRTUAL}) and also while system calls are running on the
2073 process's behalf. At zero it raises a @code{SIGPROF}.
2075 This timer is intended for profiling where a program is spending its
2076 time (by looking where it is when the timer goes off).
2079 @code{getitimer} returns the current timer value and its programmed
2080 restart value, as a list containing two pairs. Each pair is a time in
2081 seconds and microseconds: @code{((@var{interval_secs}
2082 . @var{interval_usecs}) (@var{periodic_secs}
2083 . @var{periodic_usecs}))}.
2085 @code{setitimer} sets the timer values similarly, in seconds and
2086 microseconds (which must be integers). The periodic value can be zero
2087 to have the timer run down just once. The return value is the timer's
2088 previous setting, in the same form as @code{getitimer} returns.
2091 (setitimer ITIMER_REAL
2092 5 500000 ;; first SIGALRM in 5.5 seconds time
2093 2 0) ;; then repeat every 2 seconds
2096 Although the timers are programmed in microseconds, the actual
2097 accuracy might not be that high.
2101 @node Terminals and Ptys
2102 @subsection Terminals and Ptys
2104 @deffn {Scheme Procedure} isatty? port
2105 @deffnx {C Function} scm_isatty_p (port)
2107 Return @code{#t} if @var{port} is using a serial non--file
2108 device, otherwise @code{#f}.
2111 @deffn {Scheme Procedure} ttyname port
2112 @deffnx {C Function} scm_ttyname (port)
2114 Return a string with the name of the serial terminal device
2115 underlying @var{port}.
2118 @deffn {Scheme Procedure} ctermid
2119 @deffnx {C Function} scm_ctermid ()
2121 Return a string containing the file name of the controlling
2122 terminal for the current process.
2125 @deffn {Scheme Procedure} tcgetpgrp port
2126 @deffnx {C Function} scm_tcgetpgrp (port)
2127 @cindex process group
2128 Return the process group ID of the foreground process group
2129 associated with the terminal open on the file descriptor
2130 underlying @var{port}.
2132 If there is no foreground process group, the return value is a
2133 number greater than 1 that does not match the process group ID
2134 of any existing process group. This can happen if all of the
2135 processes in the job that was formerly the foreground job have
2136 terminated, and no other job has yet been moved into the
2140 @deffn {Scheme Procedure} tcsetpgrp port pgid
2141 @deffnx {C Function} scm_tcsetpgrp (port, pgid)
2142 @cindex process group
2143 Set the foreground process group ID for the terminal used by the file
2144 descriptor underlying @var{port} to the integer @var{pgid}.
2146 must be a member of the same session as @var{pgid} and must have the same
2147 controlling terminal. The return value is unspecified.
2154 The following procedures are similar to the @code{popen} and
2155 @code{pclose} system routines. The code is in a separate ``popen''
2159 (use-modules (ice-9 popen))
2163 @deffn {Scheme Procedure} open-pipe command mode
2164 @deffnx {Scheme Procedure} open-pipe* mode prog [args...]
2165 Execute a command in a subprocess, with a pipe to it or from it, or
2166 with pipes in both directions.
2168 @code{open-pipe} runs the shell @var{command} using @samp{/bin/sh -c}.
2169 @code{open-pipe*} executes @var{prog} directly, with the optional
2170 @var{args} arguments (all strings).
2172 @var{mode} should be one of the following values. @code{OPEN_READ} is
2173 an input pipe, ie.@: to read from the subprocess. @code{OPEN_WRITE}
2174 is an output pipe, ie.@: to write to it.
2181 For an input pipe, the child's standard output is the pipe and
2182 standard input is inherited from @code{current-input-port}. For an
2183 output pipe, the child's standard input is the pipe and standard
2184 output is inherited from @code{current-output-port}. In all cases
2185 cases the child's standard error is inherited from
2186 @code{current-error-port} (@pxref{Default Ports}).
2188 If those @code{current-X-ports} are not files of some kind, and hence
2189 don't have file descriptors for the child, then @file{/dev/null} is
2192 Care should be taken with @code{OPEN_BOTH}, a deadlock will occur if
2193 both parent and child are writing, and waiting until the write
2194 completes before doing any reading. Each direction has
2195 @code{PIPE_BUF} bytes of buffering (@pxref{Ports and File
2196 Descriptors}), which will be enough for small writes, but not for say
2197 putting a big file through a filter.
2200 @deffn {Scheme Procedure} open-input-pipe command
2201 Equivalent to @code{open-pipe} with mode @code{OPEN_READ}.
2204 (let* ((port (open-input-pipe "date --utc"))
2205 (str (read-line port)))
2208 @result{} "Mon Mar 11 20:10:44 UTC 2002"
2212 @deffn {Scheme Procedure} open-output-pipe command
2213 Equivalent to @code{open-pipe} with mode @code{OPEN_WRITE}.
2216 (let ((port (open-output-pipe "lpr")))
2217 (display "Something for the line printer.\n" port)
2218 (if (not (eqv? 0 (status:exit-val (close-pipe port))))
2219 (error "Cannot print")))
2223 @deffn {Scheme Procedure} open-input-output-pipe command
2224 Equivalent to @code{open-pipe} with mode @code{OPEN_BOTH}.
2228 @deffn {Scheme Procedure} close-pipe port
2229 Close a pipe created by @code{open-pipe}, wait for the process to
2230 terminate, and return the wait status code. The status is as per
2231 @code{waitpid} and can be decoded with @code{status:exit-val} etc
2236 @code{waitpid WAIT_ANY} should not be used when pipes are open, since
2237 it can reap a pipe's child process, causing an error from a subsequent
2240 @code{close-port} (@pxref{Closing}) can close a pipe, but it doesn't
2241 reap the child process.
2243 The garbage collector will close a pipe no longer in use, and reap the
2244 child process with @code{waitpid}. If the child hasn't yet terminated
2245 the garbage collector doesn't block, but instead checks again in the
2248 Many systems have per-user and system-wide limits on the number of
2249 processes, and a system-wide limit on the number of pipes, so pipes
2250 should be closed explicitly when no longer needed, rather than letting
2251 the garbage collector pick them up at some later time.
2255 @subsection Networking
2259 * Network Address Conversion::
2260 * Network Databases::
2261 * Network Socket Address::
2262 * Network Sockets and Communication::
2263 * Internet Socket Examples::
2266 @node Network Address Conversion
2267 @subsubsection Network Address Conversion
2268 @cindex network address
2270 This section describes procedures which convert internet addresses
2271 between numeric and string formats.
2273 @subsubheading IPv4 Address Conversion
2276 An IPv4 Internet address is a 4-byte value, represented in Guile as an
2277 integer in host byte order, so that say ``0.0.0.1'' is 1, or
2278 ``1.0.0.0'' is 16777216.
2280 Some underlying C functions use network byte order for addresses,
2281 Guile converts as necessary so that at the Scheme level its host byte
2285 For a server, this can be used with @code{bind} (@pxref{Network
2286 Sockets and Communication}) to allow connections from any interface on
2290 @defvar INADDR_BROADCAST
2291 The broadcast address on the local network.
2294 @defvar INADDR_LOOPBACK
2295 The address of the local host using the loopback device, ie.@:
2299 @c INADDR_NONE is defined in the code, but serves no purpose.
2300 @c inet_addr() returns it as an error indication, but that function
2301 @c isn't provided, for the good reason that inet_aton() does the same
2302 @c job and gives an unambiguous error indication. (INADDR_NONE is a
2303 @c valid 4-byte value, in glibc it's the same as INADDR_BROADCAST.)
2305 @c @defvar INADDR_NONE
2309 @deffn {Scheme Procedure} inet-aton address
2310 @deffnx {C Function} scm_inet_aton (address)
2311 This function is deprecated in favor of @code{inet-pton}.
2313 Convert an IPv4 Internet address from printable string
2314 (dotted decimal notation) to an integer. E.g.,
2317 (inet-aton "127.0.0.1") @result{} 2130706433
2321 @deffn {Scheme Procedure} inet-ntoa inetid
2322 @deffnx {C Function} scm_inet_ntoa (inetid)
2323 This function is deprecated in favor of @code{inet-ntop}.
2325 Convert an IPv4 Internet address to a printable
2326 (dotted decimal notation) string. E.g.,
2329 (inet-ntoa 2130706433) @result{} "127.0.0.1"
2333 @deffn {Scheme Procedure} inet-netof address
2334 @deffnx {C Function} scm_inet_netof (address)
2335 Return the network number part of the given IPv4
2336 Internet address. E.g.,
2339 (inet-netof 2130706433) @result{} 127
2343 @deffn {Scheme Procedure} inet-lnaof address
2344 @deffnx {C Function} scm_lnaof (address)
2345 Return the local-address-with-network part of the given
2346 IPv4 Internet address, using the obsolete class A/B/C system.
2350 (inet-lnaof 2130706433) @result{} 1
2354 @deffn {Scheme Procedure} inet-makeaddr net lna
2355 @deffnx {C Function} scm_inet_makeaddr (net, lna)
2356 Make an IPv4 Internet address by combining the network number
2357 @var{net} with the local-address-within-network number
2361 (inet-makeaddr 127 1) @result{} 2130706433
2365 @subsubheading IPv6 Address Conversion
2368 An IPv6 Internet address is a 16-byte value, represented in Guile as
2369 an integer in host byte order, so that say ``::1'' is 1.
2371 @deffn {Scheme Procedure} inet-ntop family address
2372 @deffnx {C Function} scm_inet_ntop (family, address)
2373 Convert a network address from an integer to a printable string.
2374 @var{family} can be @code{AF_INET} or @code{AF_INET6}. E.g.,
2377 (inet-ntop AF_INET 2130706433) @result{} "127.0.0.1"
2378 (inet-ntop AF_INET6 (- (expt 2 128) 1))
2379 @result{} "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
2383 @deffn {Scheme Procedure} inet-pton family address
2384 @deffnx {C Function} scm_inet_pton (family, address)
2385 Convert a string containing a printable network address to an integer
2386 address. @var{family} can be @code{AF_INET} or @code{AF_INET6}.
2390 (inet-pton AF_INET "127.0.0.1") @result{} 2130706433
2391 (inet-pton AF_INET6 "::1") @result{} 1
2396 @node Network Databases
2397 @subsubsection Network Databases
2398 @cindex network database
2400 This section describes procedures which query various network databases.
2401 Care should be taken when using the database routines since they are not
2404 @subsubheading @code{getaddrinfo}
2406 @cindex @code{addrinfo} object type
2407 @cindex host name lookup
2408 @cindex service name lookup
2410 The @code{getaddrinfo} procedure maps host and service names to socket addresses
2411 and associated information in a protocol-independent way.
2413 @deffn {Scheme Procedure} getaddrinfo name service [hint_flags [hint_family [hint_socktype [hint_protocol]]]]
2414 @deffnx {C Function} scm_getaddrinfo (name, service, hint_flags, hint_family, hint_socktype, hint_protocol)
2415 Return a list of @code{addrinfo} structures containing
2416 a socket address and associated information for host @var{name}
2417 and/or @var{service} to be used in creating a socket with
2418 which to address the specified service.
2421 (let* ((ai (car (getaddrinfo "www.gnu.org" "http")))
2422 (s (socket (addrinfo:fam ai) (addrinfo:socktype ai)
2423 (addrinfo:protocol ai))))
2424 (connect s (addrinfo:addr ai))
2428 When @var{service} is omitted or is @code{#f}, return
2429 network-level addresses for @var{name}. When @var{name}
2430 is @code{#f} @var{service} must be provided and service
2431 locations local to the caller are returned.
2433 Additional hints can be provided. When specified,
2434 @var{hint_flags} should be a bitwise-or of zero or more
2435 constants among the following:
2439 Socket address is intended for @code{bind}.
2442 Request for canonical host name, available via
2443 @code{addrinfo:canonname}. This makes sense mainly when
2444 DNS lookups are involved.
2446 @item AI_NUMERICHOST
2447 Specifies that @var{name} is a numeric host address string
2448 (e.g., @code{"127.0.0.1"}), meaning that name resolution
2451 @item AI_NUMERICSERV
2452 Likewise, specifies that @var{service} is a numeric port
2453 string (e.g., @code{"80"}).
2456 Return only addresses configured on the local system It is
2457 highly recommended to provide this flag when the returned
2458 socket addresses are to be used to make connections;
2459 otherwise, some of the returned addresses could be unreachable
2460 or use a protocol that is not supported.
2463 When looking up IPv6 addresses, return mapped IPv4 addresses if
2464 there is no IPv6 address available at all.
2467 If this flag is set along with @code{AI_V4MAPPED} when looking up IPv6
2468 addresses, return all IPv6 addresses as well as all IPv4 addresses, the latter
2469 mapped to IPv6 format.
2472 When given, @var{hint_family} should specify the requested
2473 address family, e.g., @code{AF_INET6}. Similarly,
2474 @var{hint_socktype} should specify the requested socket type
2475 (e.g., @code{SOCK_DGRAM}), and @var{hint_protocol} should
2476 specify the requested protocol (its value is interpreted
2477 as in calls to @code{socket}).
2479 On error, an exception with key @code{getaddrinfo-error} is
2480 thrown, with an error code (an integer) as its argument:
2483 (catch 'getaddrinfo-error
2485 (getaddrinfo "www.gnu.org" "gopher"))
2486 (lambda (key errcode)
2487 (cond ((= errcode EAI_SERVICE)
2488 (display "doesn't know about Gopher!\n"))
2489 ((= errcode EAI_NONAME)
2490 (display "www.gnu.org not found\\n"))
2492 (format #t "something wrong: ~a\n"
2493 (gai-strerror errcode))))))
2500 The name or service could not be resolved at this time. Future
2501 attempts may succeed.
2504 @var{hint_flags} contains an invalid value.
2507 A non-recoverable error occurred when attempting to
2511 @var{hint_family} was not recognized.
2514 Either @var{name} does not resolve for the supplied parameters,
2515 or neither @var{name} nor @var{service} were supplied.
2518 This non-POSIX error code can be returned on some systems (GNU
2519 and Darwin, at least), for example when @var{name} is known
2520 but requests that were made turned out no data. Error handling
2521 code should be prepared to handle it when it is defined.
2524 @var{service} was not recognized for the specified socket type.
2527 @var{hint_socktype} was not recognized.
2530 A system error occurred; the error code can be found in
2534 Users are encouraged to read the
2535 @url{http://www.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html,
2536 "POSIX specification} for more details.
2539 The following procedures take an @code{addrinfo} object as returned by
2542 @deffn {Scheme Procedure} addrinfo:flags ai
2543 Return flags for @var{ai} as a bitwise or of @code{AI_} values (see above).
2546 @deffn {Scheme Procedure} addrinfo:fam ai
2547 Return the address family of @var{ai} (a @code{AF_} value).
2550 @deffn {Scheme Procedure} addrinfo:socktype ai
2551 Return the socket type for @var{ai} (a @code{SOCK_} value).
2554 @deffn {Scheme Procedure} addrinfo:protocol ai
2555 Return the protocol of @var{ai}.
2558 @deffn {Scheme Procedure} addrinfo:addr ai
2559 Return the socket address associated with @var{ai} as a @code{sockaddr}
2560 object (@pxref{Network Socket Address}).
2563 @deffn {Scheme Procedure} addrinfo:canonname ai
2564 Return a string for the canonical name associated with @var{ai} if
2565 the @code{AI_CANONNAME} flag was supplied.
2568 @subsubheading The Host Database
2569 @cindex @file{/etc/hosts}
2570 @cindex network database
2572 A @dfn{host object} is a structure that represents what is known about a
2573 network host, and is the usual way of representing a system's network
2574 identity inside software.
2576 The following functions accept a host object and return a selected
2579 @deffn {Scheme Procedure} hostent:name host
2580 The ``official'' hostname for @var{host}.
2582 @deffn {Scheme Procedure} hostent:aliases host
2583 A list of aliases for @var{host}.
2585 @deffn {Scheme Procedure} hostent:addrtype host
2586 The host address type, one of the @code{AF} constants, such as
2587 @code{AF_INET} or @code{AF_INET6}.
2589 @deffn {Scheme Procedure} hostent:length host
2590 The length of each address for @var{host}, in bytes.
2592 @deffn {Scheme Procedure} hostent:addr-list host
2593 The list of network addresses associated with @var{host}. For
2594 @code{AF_INET} these are integer IPv4 address (@pxref{Network Address
2598 The following procedures can be used to search the host database. However,
2599 @code{getaddrinfo} should be preferred over them since it's more generic and
2602 @deffn {Scheme Procedure} gethost [host]
2603 @deffnx {Scheme Procedure} gethostbyname hostname
2604 @deffnx {Scheme Procedure} gethostbyaddr address
2605 @deffnx {C Function} scm_gethost (host)
2606 Look up a host by name or address, returning a host object. The
2607 @code{gethost} procedure will accept either a string name or an integer
2608 address; if given no arguments, it behaves like @code{gethostent} (see
2609 below). If a name or address is supplied but the address can not be
2610 found, an error will be thrown to one of the keys:
2611 @code{host-not-found}, @code{try-again}, @code{no-recovery} or
2612 @code{no-data}, corresponding to the equivalent @code{h_error} values.
2613 Unusual conditions may result in errors thrown to the
2614 @code{system-error} or @code{misc_error} keys.
2617 (gethost "www.gnu.org")
2618 @result{} #("www.gnu.org" () 2 4 (3353880842))
2620 (gethostbyname "www.emacs.org")
2621 @result{} #("emacs.org" ("www.emacs.org") 2 4 (1073448978))
2625 The following procedures may be used to step through the host
2626 database from beginning to end.
2628 @deffn {Scheme Procedure} sethostent [stayopen]
2629 Initialize an internal stream from which host objects may be read. This
2630 procedure must be called before any calls to @code{gethostent}, and may
2631 also be called afterward to reset the host entry stream. If
2632 @var{stayopen} is supplied and is not @code{#f}, the database is not
2633 closed by subsequent @code{gethostbyname} or @code{gethostbyaddr} calls,
2634 possibly giving an efficiency gain.
2637 @deffn {Scheme Procedure} gethostent
2638 Return the next host object from the host database, or @code{#f} if
2639 there are no more hosts to be found (or an error has been encountered).
2640 This procedure may not be used before @code{sethostent} has been called.
2643 @deffn {Scheme Procedure} endhostent
2644 Close the stream used by @code{gethostent}. The return value is unspecified.
2647 @deffn {Scheme Procedure} sethost [stayopen]
2648 @deffnx {C Function} scm_sethost (stayopen)
2649 If @var{stayopen} is omitted, this is equivalent to @code{endhostent}.
2650 Otherwise it is equivalent to @code{sethostent stayopen}.
2653 @subsubheading The Network Database
2654 @cindex network database
2656 The following functions accept an object representing a network
2657 and return a selected component:
2659 @deffn {Scheme Procedure} netent:name net
2660 The ``official'' network name.
2662 @deffn {Scheme Procedure} netent:aliases net
2663 A list of aliases for the network.
2665 @deffn {Scheme Procedure} netent:addrtype net
2666 The type of the network number. Currently, this returns only
2669 @deffn {Scheme Procedure} netent:net net
2673 The following procedures are used to search the network database:
2675 @deffn {Scheme Procedure} getnet [net]
2676 @deffnx {Scheme Procedure} getnetbyname net-name
2677 @deffnx {Scheme Procedure} getnetbyaddr net-number
2678 @deffnx {C Function} scm_getnet (net)
2679 Look up a network by name or net number in the network database. The
2680 @var{net-name} argument must be a string, and the @var{net-number}
2681 argument must be an integer. @code{getnet} will accept either type of
2682 argument, behaving like @code{getnetent} (see below) if no arguments are
2686 The following procedures may be used to step through the network
2687 database from beginning to end.
2689 @deffn {Scheme Procedure} setnetent [stayopen]
2690 Initialize an internal stream from which network objects may be read. This
2691 procedure must be called before any calls to @code{getnetent}, and may
2692 also be called afterward to reset the net entry stream. If
2693 @var{stayopen} is supplied and is not @code{#f}, the database is not
2694 closed by subsequent @code{getnetbyname} or @code{getnetbyaddr} calls,
2695 possibly giving an efficiency gain.
2698 @deffn {Scheme Procedure} getnetent
2699 Return the next entry from the network database.
2702 @deffn {Scheme Procedure} endnetent
2703 Close the stream used by @code{getnetent}. The return value is unspecified.
2706 @deffn {Scheme Procedure} setnet [stayopen]
2707 @deffnx {C Function} scm_setnet (stayopen)
2708 If @var{stayopen} is omitted, this is equivalent to @code{endnetent}.
2709 Otherwise it is equivalent to @code{setnetent stayopen}.
2712 @subsubheading The Protocol Database
2713 @cindex @file{/etc/protocols}
2715 @cindex network protocols
2717 The following functions accept an object representing a protocol
2718 and return a selected component:
2720 @deffn {Scheme Procedure} protoent:name protocol
2721 The ``official'' protocol name.
2723 @deffn {Scheme Procedure} protoent:aliases protocol
2724 A list of aliases for the protocol.
2726 @deffn {Scheme Procedure} protoent:proto protocol
2727 The protocol number.
2730 The following procedures are used to search the protocol database:
2732 @deffn {Scheme Procedure} getproto [protocol]
2733 @deffnx {Scheme Procedure} getprotobyname name
2734 @deffnx {Scheme Procedure} getprotobynumber number
2735 @deffnx {C Function} scm_getproto (protocol)
2736 Look up a network protocol by name or by number. @code{getprotobyname}
2737 takes a string argument, and @code{getprotobynumber} takes an integer
2738 argument. @code{getproto} will accept either type, behaving like
2739 @code{getprotoent} (see below) if no arguments are supplied.
2742 The following procedures may be used to step through the protocol
2743 database from beginning to end.
2745 @deffn {Scheme Procedure} setprotoent [stayopen]
2746 Initialize an internal stream from which protocol objects may be read. This
2747 procedure must be called before any calls to @code{getprotoent}, and may
2748 also be called afterward to reset the protocol entry stream. If
2749 @var{stayopen} is supplied and is not @code{#f}, the database is not
2750 closed by subsequent @code{getprotobyname} or @code{getprotobynumber} calls,
2751 possibly giving an efficiency gain.
2754 @deffn {Scheme Procedure} getprotoent
2755 Return the next entry from the protocol database.
2758 @deffn {Scheme Procedure} endprotoent
2759 Close the stream used by @code{getprotoent}. The return value is unspecified.
2762 @deffn {Scheme Procedure} setproto [stayopen]
2763 @deffnx {C Function} scm_setproto (stayopen)
2764 If @var{stayopen} is omitted, this is equivalent to @code{endprotoent}.
2765 Otherwise it is equivalent to @code{setprotoent stayopen}.
2768 @subsubheading The Service Database
2769 @cindex @file{/etc/services}
2771 @cindex network services
2773 The following functions accept an object representing a service
2774 and return a selected component:
2776 @deffn {Scheme Procedure} servent:name serv
2777 The ``official'' name of the network service.
2779 @deffn {Scheme Procedure} servent:aliases serv
2780 A list of aliases for the network service.
2782 @deffn {Scheme Procedure} servent:port serv
2783 The Internet port used by the service.
2785 @deffn {Scheme Procedure} servent:proto serv
2786 The protocol used by the service. A service may be listed many times
2787 in the database under different protocol names.
2790 The following procedures are used to search the service database:
2792 @deffn {Scheme Procedure} getserv [name [protocol]]
2793 @deffnx {Scheme Procedure} getservbyname name protocol
2794 @deffnx {Scheme Procedure} getservbyport port protocol
2795 @deffnx {C Function} scm_getserv (name, protocol)
2796 Look up a network service by name or by service number, and return a
2797 network service object. The @var{protocol} argument specifies the name
2798 of the desired protocol; if the protocol found in the network service
2799 database does not match this name, a system error is signalled.
2801 The @code{getserv} procedure will take either a service name or number
2802 as its first argument; if given no arguments, it behaves like
2803 @code{getservent} (see below).
2806 (getserv "imap" "tcp")
2807 @result{} #("imap2" ("imap") 143 "tcp")
2809 (getservbyport 88 "udp")
2810 @result{} #("kerberos" ("kerberos5" "krb5") 88 "udp")
2814 The following procedures may be used to step through the service
2815 database from beginning to end.
2817 @deffn {Scheme Procedure} setservent [stayopen]
2818 Initialize an internal stream from which service objects may be read. This
2819 procedure must be called before any calls to @code{getservent}, and may
2820 also be called afterward to reset the service entry stream. If
2821 @var{stayopen} is supplied and is not @code{#f}, the database is not
2822 closed by subsequent @code{getservbyname} or @code{getservbyport} calls,
2823 possibly giving an efficiency gain.
2826 @deffn {Scheme Procedure} getservent
2827 Return the next entry from the services database.
2830 @deffn {Scheme Procedure} endservent
2831 Close the stream used by @code{getservent}. The return value is unspecified.
2834 @deffn {Scheme Procedure} setserv [stayopen]
2835 @deffnx {C Function} scm_setserv (stayopen)
2836 If @var{stayopen} is omitted, this is equivalent to @code{endservent}.
2837 Otherwise it is equivalent to @code{setservent stayopen}.
2841 @node Network Socket Address
2842 @subsubsection Network Socket Address
2843 @cindex socket address
2844 @cindex network socket address
2845 @tpindex Socket address
2847 A @dfn{socket address} object identifies a socket endpoint for
2848 communication. In the case of @code{AF_INET} for instance, the socket
2849 address object comprises the host address (or interface on the host)
2850 and a port number which specifies a particular open socket in a
2851 running client or server process. A socket address object can be
2854 @deffn {Scheme Procedure} make-socket-address AF_INET ipv4addr port
2855 @deffnx {Scheme Procedure} make-socket-address AF_INET6 ipv6addr port [flowinfo [scopeid]]
2856 @deffnx {Scheme Procedure} make-socket-address AF_UNIX path
2857 @deffnx {C Function} scm_make_socket_address (family, address, arglist)
2858 Return a new socket address object. The first argument is the address
2859 family, one of the @code{AF} constants, then the arguments vary
2860 according to the family.
2862 For @code{AF_INET} the arguments are an IPv4 network address number
2863 (@pxref{Network Address Conversion}), and a port number.
2865 For @code{AF_INET6} the arguments are an IPv6 network address number
2866 and a port number. Optional @var{flowinfo} and @var{scopeid}
2867 arguments may be given (both integers, default 0).
2869 For @code{AF_UNIX} the argument is a filename (a string).
2871 The C function @code{scm_make_socket_address} takes the @var{family}
2872 and @var{address} arguments directly, then @var{arglist} is a list of
2873 further arguments, being the port for IPv4, port and optional flowinfo
2874 and scopeid for IPv6, or the empty list @code{SCM_EOL} for Unix
2879 The following functions access the fields of a socket address object,
2881 @deffn {Scheme Procedure} sockaddr:fam sa
2882 Return the address family from socket address object @var{sa}. This
2883 is one of the @code{AF} constants (e.g.@: @code{AF_INET}).
2886 @deffn {Scheme Procedure} sockaddr:path sa
2887 For an @code{AF_UNIX} socket address object @var{sa}, return the
2891 @deffn {Scheme Procedure} sockaddr:addr sa
2892 For an @code{AF_INET} or @code{AF_INET6} socket address object
2893 @var{sa}, return the network address number.
2896 @deffn {Scheme Procedure} sockaddr:port sa
2897 For an @code{AF_INET} or @code{AF_INET6} socket address object
2898 @var{sa}, return the port number.
2901 @deffn {Scheme Procedure} sockaddr:flowinfo sa
2902 For an @code{AF_INET6} socket address object @var{sa}, return the
2906 @deffn {Scheme Procedure} sockaddr:scopeid sa
2907 For an @code{AF_INET6} socket address object @var{sa}, return the
2911 @tpindex @code{struct sockaddr}
2912 @tpindex @code{sockaddr}
2913 The functions below convert to and from the C @code{struct sockaddr}
2914 (@pxref{Address Formats,,, libc, The GNU C Library Reference Manual}).
2915 That structure is a generic type, an application can cast to or from
2916 @code{struct sockaddr_in}, @code{struct sockaddr_in6} or @code{struct
2917 sockaddr_un} according to the address family.
2919 In a @code{struct sockaddr} taken or returned, the byte ordering in
2920 the fields follows the C conventions (@pxref{Byte Order,, Byte Order
2921 Conversion, libc, The GNU C Library Reference Manual}). This means
2922 network byte order for @code{AF_INET} host address
2923 (@code{sin_addr.s_addr}) and port number (@code{sin_port}), and
2924 @code{AF_INET6} port number (@code{sin6_port}). But at the Scheme
2925 level these values are taken or returned in host byte order, so the
2926 port is an ordinary integer, and the host address likewise is an
2927 ordinary integer (as described in @ref{Network Address Conversion}).
2929 @deftypefn {C Function} {struct sockaddr *} scm_c_make_socket_address (SCM family, SCM address, SCM args, size_t *outsize)
2930 Return a newly-@code{malloc}ed @code{struct sockaddr} created from
2931 arguments like those taken by @code{scm_make_socket_address} above.
2933 The size (in bytes) of the @code{struct sockaddr} return is stored
2934 into @code{*@var{outsize}}. An application must call @code{free} to
2935 release the returned structure when no longer required.
2938 @deftypefn {C Function} SCM scm_from_sockaddr (const struct sockaddr *address, unsigned address_size)
2939 Return a Scheme socket address object from the C @var{address}
2940 structure. @var{address_size} is the size in bytes of @var{address}.
2943 @deftypefn {C Function} {struct sockaddr *} scm_to_sockaddr (SCM address, size_t *address_size)
2944 Return a newly-@code{malloc}ed @code{struct sockaddr} from a Scheme
2945 level socket address object.
2947 The size (in bytes) of the @code{struct sockaddr} return is stored
2948 into @code{*@var{outsize}}. An application must call @code{free} to
2949 release the returned structure when no longer required.
2953 @node Network Sockets and Communication
2954 @subsubsection Network Sockets and Communication
2956 @cindex network socket
2958 Socket ports can be created using @code{socket} and @code{socketpair}.
2959 The ports are initially unbuffered, to make reading and writing to the
2960 same port more reliable. A buffer can be added to the port using
2961 @code{setvbuf}; see @ref{Ports and File Descriptors}.
2963 Most systems have limits on how many files and sockets can be open, so
2964 it's strongly recommended that socket ports be closed explicitly when
2965 no longer required (@pxref{Ports}).
2967 Some of the underlying C functions take values in network byte order,
2968 but the convention in Guile is that at the Scheme level everything is
2969 ordinary host byte order and conversions are made automatically where
2972 @deffn {Scheme Procedure} socket family style proto
2973 @deffnx {C Function} scm_socket (family, style, proto)
2974 Return a new socket port of the type specified by @var{family},
2975 @var{style} and @var{proto}. All three parameters are integers. The
2976 possible values for @var{family} are as follows, where supported by
2984 The possible values for @var{style} are as follows, again where
2985 supported by the system,
2991 @defvarx SOCK_SEQPACKET
2994 @var{proto} can be obtained from a protocol name using
2995 @code{getprotobyname} (@pxref{Network Databases}). A value of zero
2996 means the default protocol, which is usually right.
2998 A socket cannot by used for communication until it has been connected
2999 somewhere, usually with either @code{connect} or @code{accept} below.
3002 @deffn {Scheme Procedure} socketpair family style proto
3003 @deffnx {C Function} scm_socketpair (family, style, proto)
3004 Return a pair, the @code{car} and @code{cdr} of which are two unnamed
3005 socket ports connected to each other. The connection is full-duplex,
3006 so data can be transferred in either direction between the two.
3008 @var{family}, @var{style} and @var{proto} are as per @code{socket}
3009 above. But many systems only support socket pairs in the
3010 @code{PF_UNIX} family. Zero is likely to be the only meaningful value
3014 @deffn {Scheme Procedure} getsockopt sock level optname
3015 @deffnx {Scheme Procedure} setsockopt sock level optname value
3016 @deffnx {C Function} scm_getsockopt (sock, level, optname)
3017 @deffnx {C Function} scm_setsockopt (sock, level, optname, value)
3018 Get or set an option on socket port @var{sock}. @code{getsockopt}
3019 returns the current value. @code{setsockopt} sets a value and the
3020 return is unspecified.
3022 @var{level} is an integer specifying a protocol layer, either
3023 @code{SOL_SOCKET} for socket level options, or a protocol number from
3024 the @code{IPPROTO} constants or @code{getprotoent} (@pxref{Network
3029 @defvarx IPPROTO_TCP
3030 @defvarx IPPROTO_UDP
3033 @var{optname} is an integer specifying an option within the protocol
3036 For @code{SOL_SOCKET} level the following @var{optname}s are defined
3037 (when provided by the system). For their meaning see
3038 @ref{Socket-Level Options,,, libc, The GNU C Library Reference
3039 Manual}, or @command{man 7 socket}.
3042 @defvarx SO_REUSEADDR
3046 @defvarx SO_DONTROUTE
3047 @defvarx SO_BROADCAST
3050 @defvarx SO_KEEPALIVE
3051 @defvarx SO_OOBINLINE
3052 @defvarx SO_NO_CHECK
3053 @defvarx SO_PRIORITY
3054 The @var{value} taken or returned is an integer.
3058 The @var{value} taken or returned is a pair of integers
3059 @code{(@var{ENABLE} . @var{TIMEOUT})}. On old systems without timeout
3060 support (ie.@: without @code{struct linger}), only @var{ENABLE} has an
3061 effect but the value in Guile is always a pair.
3064 @c Note that we refer only to ``man ip'' here. On GNU/Linux it's
3065 @c ``man 7 ip'' but on NetBSD it's ``man 4 ip''.
3067 For IP level (@code{IPPROTO_IP}) the following @var{optname}s are
3068 defined (when provided by the system). See @command{man ip} for what
3071 @defvar IP_MULTICAST_IF
3072 This sets the source interface used by multicast traffic.
3075 @defvar IP_MULTICAST_TTL
3076 This sets the default TTL for multicast traffic. This defaults
3077 to 1 and should be increased to allow traffic to pass beyond the
3081 @defvar IP_ADD_MEMBERSHIP
3082 @defvarx IP_DROP_MEMBERSHIP
3083 These can be used only with @code{setsockopt}, not @code{getsockopt}.
3084 @var{value} is a pair @code{(@var{MULTIADDR} . @var{INTERFACEADDR})}
3085 of integer IPv4 addresses (@pxref{Network Address Conversion}).
3086 @var{MULTIADDR} is a multicast address to be added to or dropped from
3087 the interface @var{INTERFACEADDR}. @var{INTERFACEADDR} can be
3088 @code{INADDR_ANY} to have the system select the interface.
3089 @var{INTERFACEADDR} can also be an interface index number, on systems
3094 @deffn {Scheme Procedure} shutdown sock how
3095 @deffnx {C Function} scm_shutdown (sock, how)
3096 Sockets can be closed simply by using @code{close-port}. The
3097 @code{shutdown} procedure allows reception or transmission on a
3098 connection to be shut down individually, according to the parameter
3103 Stop receiving data for this socket. If further data arrives, reject it.
3105 Stop trying to transmit data from this socket. Discard any
3106 data waiting to be sent. Stop looking for acknowledgement of
3107 data already sent; don't retransmit it if it is lost.
3109 Stop both reception and transmission.
3112 The return value is unspecified.
3115 @deffn {Scheme Procedure} connect sock sockaddr
3116 @deffnx {Scheme Procedure} connect sock AF_INET ipv4addr port
3117 @deffnx {Scheme Procedure} connect sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
3118 @deffnx {Scheme Procedure} connect sock AF_UNIX path
3119 @deffnx {C Function} scm_connect (sock, fam, address, args)
3120 Initiate a connection on socket port @var{sock} to a given address.
3121 The destination is either a socket address object, or arguments the
3122 same as @code{make-socket-address} would take to make such an object
3123 (@pxref{Network Socket Address}). The return value is unspecified.
3126 (connect sock AF_INET INADDR_LOOPBACK 23)
3127 (connect sock (make-socket-address AF_INET INADDR_LOOPBACK 23))
3131 @deffn {Scheme Procedure} bind sock sockaddr
3132 @deffnx {Scheme Procedure} bind sock AF_INET ipv4addr port
3133 @deffnx {Scheme Procedure} bind sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
3134 @deffnx {Scheme Procedure} bind sock AF_UNIX path
3135 @deffnx {C Function} scm_bind (sock, fam, address, args)
3136 Bind socket port @var{sock} to the given address. The address is
3137 either a socket address object, or arguments the same as
3138 @code{make-socket-address} would take to make such an object
3139 (@pxref{Network Socket Address}). The return value is unspecified.
3141 Generally a socket is only explicitly bound to a particular address
3142 when making a server, i.e.@: to listen on a particular port. For an
3143 outgoing connection the system will assign a local address
3144 automatically, if not already bound.
3147 (bind sock AF_INET INADDR_ANY 12345)
3148 (bind sock (make-socket-address AF_INET INADDR_ANY 12345))
3152 @deffn {Scheme Procedure} listen sock backlog
3153 @deffnx {C Function} scm_listen (sock, backlog)
3154 Enable @var{sock} to accept connection
3155 requests. @var{backlog} is an integer specifying
3156 the maximum length of the queue for pending connections.
3157 If the queue fills, new clients will fail to connect until
3158 the server calls @code{accept} to accept a connection from
3161 The return value is unspecified.
3164 @deffn {Scheme Procedure} accept sock
3165 @deffnx {C Function} scm_accept (sock)
3166 Accept a connection from socket port @var{sock} which has been enabled
3167 for listening with @code{listen} above. If there are no incoming
3168 connections in the queue, wait until one is available (unless
3169 @code{O_NONBLOCK} has been set on the socket, @pxref{Ports and File
3170 Descriptors,@code{fcntl}}).
3172 The return value is a pair. The @code{car} is a new socket port,
3173 connected and ready to communicate. The @code{cdr} is a socket
3174 address object (@pxref{Network Socket Address}) which is where the
3175 remote connection is from (like @code{getpeername} below).
3177 All communication takes place using the new socket returned. The
3178 given @var{sock} remains bound and listening, and @code{accept} may be
3179 called on it again to get another incoming connection when desired.
3182 @deffn {Scheme Procedure} getsockname sock
3183 @deffnx {C Function} scm_getsockname (sock)
3184 Return a socket address object which is the where @var{sock} is bound
3185 locally. @var{sock} may have obtained its local address from
3186 @code{bind} (above), or if a @code{connect} is done with an otherwise
3187 unbound socket (which is usual) then the system will have assigned an
3190 Note that on many systems the address of a socket in the
3191 @code{AF_UNIX} namespace cannot be read.
3194 @deffn {Scheme Procedure} getpeername sock
3195 @deffnx {C Function} scm_getpeername (sock)
3196 Return a socket address object which is where @var{sock} is connected
3197 to, i.e.@: the remote endpoint.
3199 Note that on many systems the address of a socket in the
3200 @code{AF_UNIX} namespace cannot be read.
3203 @deffn {Scheme Procedure} recv! sock buf [flags]
3204 @deffnx {C Function} scm_recv (sock, buf, flags)
3205 Receive data from a socket port.
3206 @var{sock} must already
3207 be bound to the address from which data is to be received.
3208 @var{buf} is a bytevector into which
3209 the data will be written. The size of @var{buf} limits
3211 data which can be received: in the case of packet
3212 protocols, if a packet larger than this limit is encountered
3214 will be irrevocably lost.
3218 @vindex MSG_DONTROUTE
3219 The optional @var{flags} argument is a value or bitwise OR of
3220 @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3222 The value returned is the number of bytes read from the
3225 Note that the data is read directly from the socket file
3227 any unread buffered port data is ignored.
3230 @deffn {Scheme Procedure} send sock message [flags]
3231 @deffnx {C Function} scm_send (sock, message, flags)
3234 @vindex MSG_DONTROUTE
3235 Transmit bytevector @var{message} on socket port @var{sock}.
3236 @var{sock} must already be bound to a destination address. The value
3237 returned is the number of bytes transmitted---it's possible for this
3238 to be less than the length of @var{message} if the socket is set to be
3239 non-blocking. The optional @var{flags} argument is a value or bitwise
3240 OR of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3242 Note that the data is written directly to the socket
3244 any unflushed buffered port data is ignored.
3247 @deffn {Scheme Procedure} recvfrom! sock buf [flags [start [end]]]
3248 @deffnx {C Function} scm_recvfrom (sock, buf, flags, start, end)
3249 Receive data from socket port @var{sock}, returning the originating
3250 address as well as the data. This function is usually for datagram
3251 sockets, but can be used on stream-oriented sockets too.
3253 The data received is stored in bytevector @var{buf}, using
3254 either the whole bytevector or just the region between the optional
3255 @var{start} and @var{end} positions. The size of @var{buf}
3256 limits the amount of data that can be received. For datagram
3257 protocols if a packet larger than this is received then excess
3258 bytes are irrevocably lost.
3260 The return value is a pair. The @code{car} is the number of bytes
3261 read. The @code{cdr} is a socket address object (@pxref{Network
3262 Socket Address}) which is where the data came from, or @code{#f} if
3263 the origin is unknown.
3267 @vindex MSG_DONTROUTE
3268 The optional @var{flags} argument is a or bitwise-OR (@code{logior})
3269 of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3271 Data is read directly from the socket file descriptor, any buffered
3272 port data is ignored.
3274 @c This was linux kernel 2.6.15 and glibc 2.3.6, not sure what any
3275 @c specs are supposed to say about recvfrom threading.
3277 On a GNU/Linux system @code{recvfrom!} is not multi-threading, all
3278 threads stop while a @code{recvfrom!} call is in progress. An
3279 application may need to use @code{select}, @code{O_NONBLOCK} or
3280 @code{MSG_DONTWAIT} to avoid this.
3283 @deffn {Scheme Procedure} sendto sock message sockaddr [flags]
3284 @deffnx {Scheme Procedure} sendto sock message AF_INET ipv4addr port [flags]
3285 @deffnx {Scheme Procedure} sendto sock message AF_INET6 ipv6addr port [flowinfo [scopeid [flags]]]
3286 @deffnx {Scheme Procedure} sendto sock message AF_UNIX path [flags]
3287 @deffnx {C Function} scm_sendto (sock, message, fam, address, args_and_flags)
3288 Transmit bytevector @var{message} as a datagram socket port
3289 @var{sock}. The destination is specified either as a socket address
3290 object, or as arguments the same as would be taken by
3291 @code{make-socket-address} to create such an object (@pxref{Network
3294 The destination address may be followed by an optional @var{flags}
3295 argument which is a @code{logior} (@pxref{Bitwise Operations}) of
3296 @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.
3298 The value returned is the number of bytes transmitted --
3300 this to be less than the length of @var{message} if the
3302 set to be non-blocking.
3303 Note that the data is written directly to the socket
3305 any unflushed buffered port data is ignored.
3308 The following functions can be used to convert short and long integers
3309 between ``host'' and ``network'' order. Although the procedures above do
3310 this automatically for addresses, the conversion will still need to
3311 be done when sending or receiving encoded integer data from the network.
3313 @deffn {Scheme Procedure} htons value
3314 @deffnx {C Function} scm_htons (value)
3315 Convert a 16 bit quantity from host to network byte ordering.
3316 @var{value} is packed into 2 bytes, which are then converted
3317 and returned as a new integer.
3320 @deffn {Scheme Procedure} ntohs value
3321 @deffnx {C Function} scm_ntohs (value)
3322 Convert a 16 bit quantity from network to host byte ordering.
3323 @var{value} is packed into 2 bytes, which are then converted
3324 and returned as a new integer.
3327 @deffn {Scheme Procedure} htonl value
3328 @deffnx {C Function} scm_htonl (value)
3329 Convert a 32 bit quantity from host to network byte ordering.
3330 @var{value} is packed into 4 bytes, which are then converted
3331 and returned as a new integer.
3334 @deffn {Scheme Procedure} ntohl value
3335 @deffnx {C Function} scm_ntohl (value)
3336 Convert a 32 bit quantity from network to host byte ordering.
3337 @var{value} is packed into 4 bytes, which are then converted
3338 and returned as a new integer.
3341 These procedures are inconvenient to use at present, but consider:
3344 (define write-network-long
3345 (lambda (value port)
3346 (let ((v (make-uniform-vector 1 1 0)))
3347 (uniform-vector-set! v 0 (htonl value))
3348 (uniform-vector-write v port))))
3350 (define read-network-long
3352 (let ((v (make-uniform-vector 1 1 0)))
3353 (uniform-vector-read! v port)
3354 (ntohl (uniform-vector-ref v 0)))))
3358 @node Internet Socket Examples
3359 @subsubsection Network Socket Examples
3360 @cindex network examples
3361 @cindex socket examples
3363 The following give examples of how to use network sockets.
3365 @subsubheading Internet Socket Client Example
3367 @cindex socket client example
3368 The following example demonstrates an Internet socket client.
3369 It connects to the HTTP daemon running on the local machine and
3370 returns the contents of the root index URL.
3373 (let ((s (socket PF_INET SOCK_STREAM 0)))
3374 (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 80)
3375 (display "GET / HTTP/1.0\r\n\r\n" s)
3377 (do ((line (read-line s) (read-line s)))
3378 ((eof-object? line))
3384 @subsubheading Internet Socket Server Example
3386 @cindex socket server example
3387 The following example shows a simple Internet server which listens on
3388 port 2904 for incoming connections and sends a greeting back to the
3392 (let ((s (socket PF_INET SOCK_STREAM 0)))
3393 (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
3394 ;; @r{Specific address?}
3395 ;; @r{(bind s AF_INET (inet-pton AF_INET "127.0.0.1") 2904)}
3396 (bind s AF_INET INADDR_ANY 2904)
3399 (simple-format #t "Listening for clients in pid: ~S" (getpid))
3403 (let* ((client-connection (accept s))
3404 (client-details (cdr client-connection))
3405 (client (car client-connection)))
3406 (simple-format #t "Got new client connection: ~S"
3409 (simple-format #t "Client address: ~S"
3411 (sockaddr:addr client-details)))
3413 ;; @r{Send back the greeting to the client port}
3414 (display "Hello client\r\n" client)
3419 @node System Identification
3420 @subsection System Identification
3423 This section lists the various procedures Guile provides for accessing
3424 information about the system it runs on.
3426 @deffn {Scheme Procedure} uname
3427 @deffnx {C Function} scm_uname ()
3428 Return an object with some information about the computer
3429 system the program is running on.
3431 The following procedures accept an object as returned by @code{uname}
3432 and return a selected component (all of which are strings).
3434 @deffn {Scheme Procedure} utsname:sysname un
3435 The name of the operating system.
3437 @deffn {Scheme Procedure} utsname:nodename un
3438 The network name of the computer.
3440 @deffn {Scheme Procedure} utsname:release un
3441 The current release level of the operating system implementation.
3443 @deffn {Scheme Procedure} utsname:version un
3444 The current version level within the release of the operating system.
3446 @deffn {Scheme Procedure} utsname:machine un
3447 A description of the hardware.
3451 @deffn {Scheme Procedure} gethostname
3452 @deffnx {C Function} scm_gethostname ()
3454 Return the host name of the current processor.
3457 @deffn {Scheme Procedure} sethostname name
3458 @deffnx {C Function} scm_sethostname (name)
3459 Set the host name of the current processor to @var{name}. May
3460 only be used by the superuser. The return value is not
3468 @deffn {Scheme Procedure} setlocale category [locale]
3469 @deffnx {C Function} scm_setlocale (category, locale)
3470 Get or set the current locale, used for various internationalizations.
3471 Locales are strings, such as @samp{sv_SE}.
3473 If @var{locale} is given then the locale for the given @var{category}
3474 is set and the new value returned. If @var{locale} is not given then
3475 the current value is returned. @var{category} should be one of the
3476 following values (@pxref{Locale Categories, Categories of Activities
3477 that Locales Affect,, libc, The GNU C Library Reference Manual}):
3482 @defvarx LC_MESSAGES
3483 @defvarx LC_MONETARY
3489 A common usage is @samp{(setlocale LC_ALL "")}, which initializes all
3490 categories based on standard environment variables (@code{LANG} etc).
3491 For full details on categories and locale names @pxref{Locales,,
3492 Locales and Internationalization, libc, The GNU C Library Reference
3495 Note that @code{setlocale} affects locale settings for the whole
3496 process. @xref{i18n Introduction, locale objects and
3497 @code{make-locale}}, for a thread-safe alternative.
3501 @subsection Encryption
3504 Please note that the procedures in this section are not suited for
3505 strong encryption, they are only interfaces to the well-known and
3506 common system library functions of the same name. They are just as good
3507 (or bad) as the underlying functions, so you should refer to your system
3508 documentation before using them (@pxref{crypt,, Encrypting Passwords,
3509 libc, The GNU C Library Reference Manual}).
3511 @deffn {Scheme Procedure} crypt key salt
3512 @deffnx {C Function} scm_crypt (key, salt)
3513 Encrypt @var{key}, with the addition of @var{salt} (both strings),
3514 using the @code{crypt} C library call.
3517 Although @code{getpass} is not an encryption procedure per se, it
3518 appears here because it is often used in combination with @code{crypt}:
3520 @deffn {Scheme Procedure} getpass prompt
3521 @deffnx {C Function} scm_getpass (prompt)
3523 Display @var{prompt} to the standard error output and read
3524 a password from @file{/dev/tty}. If this file is not
3525 accessible, it reads from standard input. The password may be
3526 up to 127 characters in length. Additional characters and the
3527 terminating newline character are discarded. While reading
3528 the password, echoing and the generation of signals by special
3529 characters is disabled.
3534 @c TeX-master: "guile.texi"