Go to the first, previous, next, last section, table of contents.


Packages

Compiling And Linking

Function: compile-file name1 name2 ...
If the HOBBIT compiler is installed in the (implementation-vicinity), compiles the files name1 name2 ... to an object file name name1<object-suffix>, where <object-suffix> is the object file suffix for your computer (for instance, `.o'). name1 must be in the current directory; name2 ... can be in other directories.

Function: link-named-scm name module1 ...
Creates a new SCM executable with name name. name will include the object modules module1 ... which can be produced with compile-file.

cd ~/scm/
scm -e'(link-named-scm"cute""cube")'
(delete-file "scmflags.h")
(call-with-output-file
  "scmflags.h"
  (lambda (fp)
    (for-each
      (lambda (string) (write-line string fp))
      '("#define IMPLINIT \"/home/jaffer/scm/Init5c4.scm\""
        "#define COMPILED_INITS init_cube();"
        "#define BIGNUMS"
        "#define FLOATS"
        "#define ARRAYS"))))
(system "gcc -Wall -O2 -c continue.c findexec.c time.c
 repl.c scl.c eval.c sys.c subr.c unif.c rope.c scm.c")
...
scm.c: In function `scm_init_extensions':
scm.c:95: warning: implicit declaration of function `init_cube'
scm.c: In function `scm_cat_path':
scm.c:589: warning: implicit declaration of function `realloc'
scm.c:594: warning: implicit declaration of function `malloc'
scm.c: In function `scm_try_path':
scm.c:612: warning: implicit declaration of function `free'
(system "cc -o cute continue.o findexec.o time.o repl.o scl.o
 eval.o sys.o subr.o unif.o rope.o scm.o cube.o  -lm -lc")

Compilation finished at Sun Jul 21 00:59:17

Dynamic Linking

If SCM has been compiled with `dynl.c' then the additional properties of load and ([SLIB]) require specified here are supported. The require form is preferred.

Function: require feature
If the symbol feature has not already been given as an argument to require, then the object and library files associated with feature will be dynamically-linked, and an unspecified value returned. If feature is not found in *catalog*, then an error is signaled.

Function: usr:lib lib
Returns the pathname of the C library named lib. For example: (usr:lib "m") returns "/usr/lib/libm.a", the path of the C math library.

Function: x:lib lib
Returns the pathname of the X library named lib. For example: (x:lib "X11") returns "/usr/X11/lib/libX11.sa", the path of the X11 library.

Function: load filename lib1 ...
In addition to the [R4RS] requirement of loading Scheme expressions if filename is a Scheme source file, load will also dynamically load/link object files (produced by compile-file, for instance). The object-suffix need not be given to load. For example,

(load (in-vicinity (implementation-vicinity) "sc2"))
or (load (in-vicinity (implementation-vicinity) "sc2.o"))
or (require 'rev2-procedures)
or (require 'rev3-procedures)

will load/link `sc2.o' if it exists.

The lib1 ... pathnames specify additional libraries which may be needed for object files not produced by the Hobbit compiler. For instance, crs is linked on Linux by

(load (in-vicinity (implementation-vicinity) "crs.o")
      (usr:lib "ncurses") (usr:lib "c"))
or (require 'curses)

Turtlegr graphics library is linked by:

(load (in-vicinity (implementation-vicinity) "turtlegr")
      (usr:lib "X11") (usr:lib "c") (usr:lib "m"))
or (require 'turtle-graphics)

And the string regular expression (see section Regular Expression Pattern Matching) package is linked by:

(load (in-vicinity (implementation-vicinity) "rgx") (usr:lib "c"))

or

(require 'regex)

The following functions comprise the low-level Scheme interface to dynamic linking. See the file `Link.scm' in the SCM distribution for an example of their use.

Function: dyn:link filename
filename should be a string naming an object or archive file, the result of C-compiling. The dyn:link procedure links and loads filename into the current SCM session. If successfull, dyn:link returns a link-token suitable for passing as the second argument to dyn:call. If not successful, #f is returned.

Function: dyn:call name link-token
link-token should be the value returned by a call to dyn:link. name should be the name of C function of no arguments defined in the file named filename which was succesfully dyn:linked in the current SCM session. The dyn:call procedure calls the C function corresponding to name. If successful, dyn:call returns #t; If not successful, #f is returned.

dyn:call is used to call the init_... function after loading SCM object files. The init_... function then makes the identifiers defined in the file accessible as Scheme procedures.

Function: dyn:main-call name link-token arg1 ...
link-token should be the value returned by a call to dyn:link. name should be the name of C function of 2 arguments, (int argc, char **argv), defined in the file named filename which was succesfully dyn:linked in the current SCM session. The dyn:main-call procedure calls the C function corresponding to name with argv style arguments, such as are given to C main functions. If successful, dyn:main-call returns the integer returned from the call to name.

dyn:main-call can be used to call a main procedure from SCM. For example, I link in and dyn:main-call a large C program, the low level routines of which callback (see section Callbacks) into SCM (which emulates PCI hardware).

Function: dyn:unlink link-token
link-token should be the value returned by a call to dyn:link. The dyn:unlink procedure removes the previously loaded file from the current SCM session. If successful, dyn:unlink returns #t; If not successful, #f is returned.

Dump

Dump, (also known as unexec), saves the continuation of an entire SCM session to an executable file, which can then be invoked as a program. Dumped executables start very quickly, since no Scheme code has to be loaded.

There are constraints on which sessions are savable using dump

Function: dump newpath
Function: dump newpath #f
Function: dump newpath #t
Function: dump newpath thunk

dump may set the values of boot-tail, *argv*, restart, and *interactive*. dump returns an unspecified value.

When a dumped executable is invoked, the variable *interactive* (see section Internal State) has the value it possessed when dump created it. Calling dump with a single argument sets *interactive* to #f, which is the state it has at the beginning of command line processing.

The procedure program-arguments returns the command line arguments for the curent invocation. More specifically, program-arguments for the restored session are not saved from the dumping session. Command line processing is done on the value of the identifier *argv*.

The thunk boot-tail is called by SCM to process command line arguments. dump sets boot-tail to the thunk it is called with.

The following example shows how to create `rscm', which is like regular scm, but which loads faster and has the `random' package alreadly provided.

bash$ scm -rrandom
> (dump "rscm")
#<unspecified>
> (quit)
bash$ ./rscm -lpi.scm -e"(pi (random 200) 5)"
00003 14159 26535 89793 23846 26433 83279 50288 41971 69399
37510 58209 74944 59230 78164 06286 20899 86280 34825 34211
70679 82148 08651 32823 06647 09384 46095 50582 23172 53594
08128 48111 74502 84102 70193 85211 05559 64462 29489 
bash$ 

This task can also be accomplished using the `-o' command line option (see section Options).

bash$ scm -rrandom -o rscm
> (quit)
bash$ ./rscm -lpi.scm -e"(pi (random 200) 5)"
00003 14159 26535 89793 23846 26433 83279 50288 41971 69399
37510 58209 74944 59230 78164 06286 20899 86280 34825 34211
70679 82148 08651 32823 06647 09384 46095 50582 23172 53594
08128 48111 74502 84102 70193 85211 05559 64462 29489 
bash$ 

Numeric

Constant: most-positive-fixnum
The immediate integer closest to positive infinity. See section `Configuration' in SLIB.

Constant: most-negative-fixnum
The immediate integer closest to negative infinity.

These procedures augment the standard capabilities in section `Numerical operations' in Revised(4) Scheme.

Function: sinh z
Function: cosh z
Function: tanh z
Return the hyperbolic sine, cosine, and tangent of z

Function: asinh z
Function: acosh z
Function: atanh z
Return the inverse hyperbolic sine, cosine, and tangent of z

Function: $sqrt x
Function: $abs x
Function: $exp x
Function: $log x
Function: $sin x
Function: $cos x
Function: $tan x
Function: $asin x
Function: $acos x
Function: $atan x

Function: $sinh x
Function: $cosh x
Function: $tanh x
Function: $asinh x
Function: $acosh x
Function: $atanh x
Real-only versions of these popular functions. The argument x must be a real number. It is an error if the value which should be returned by a call to these procedures is not real.

Function: $log10 x
Real-only base 10 logarithm.

Function: $atan2 y x
Computes (angle (make-rectangular x y)) for real numbers y and x.

Function: $expt x1 x2
Returns real number x1 raised to the real power x2. It is an error if the value which should be returned by a call to $expt is not real.

Arrays

Conventional Arrays

Arrays read and write as a # followed by the rank (number of dimensions) followed by what appear as lists (of lists) of elements. The lists must be nested to the depth of the rank. For each depth, all lists must be the same length.

(make-array 'ho 3 3) =>
#2((ho ho ho) (ho ho ho) (ho ho ho))

Unshared conventional (not uniform) 0-based arrays of rank 1 (dimension) are equivalent to (and can't be distinguished from) vectors.

(make-array 'ho 3) => (ho ho ho)

When constructing an array, bound is either an inclusive range of indices expressed as a two element list, or an upper bound expressed as a single integer. So

(make-array 'foo 3 3) == (make-array 'foo '(0 2) '(0 2))

Function: array? obj
Returns #t if the obj is an array, and #f if not.

Function: make-array initial-value bound1 bound2 ...
Creates and returns an array that has as many dimensions as there are bounds and fills it with initial-value.

Function: array-ref array index1 index2 ...
Returns the index1, index2, ...'th element of array.

Function: array-in-bounds? array index1 index2 ...
Returns #t if its arguments would be acceptable to array-ref.

Function: array-set! array new-value index1 index2 ...
Sets the index1, index2, ...'th element of array to new-value. The value returned by array-set! is unspecified.

Function: make-shared-array array mapper bound1 bound2 ...
make-shared-array can be used to create shared subarrays of other arrays. The mapper is a function that translates coordinates in the new array into coordinates in the old array. A mapper must be linear, and its range must stay within the bounds of the old array, but it can be otherwise arbitrary. A simple example:
(define fred (make-array #f 8 8))
(define freds-diagonal
  (make-shared-array fred (lambda (i) (list i i)) 8))
(array-set! freds-diagonal 'foo 3)
(array-ref fred 3 3) => foo
(define freds-center
  (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
(array-ref freds-center 0 0) => foo

Function: transpose-array array dim0 dim1 ...
Returns an array sharing contents with array, but with dimensions arranged in a different order. There must be one dim argument for each dimension of array. dim0, dim1, ... should be integers between 0 and the rank of the array to be returned. Each integer in that range must appear at least once in the argument list.

The values of dim0, dim1, ... correspond to dimensions in the array to be returned, their positions in the argument list to dimensions of array. Several dims may have the same value, in which case the returned array will have smaller rank than array.

examples:

(transpose-array '#2((a b) (c d)) 1 0) => #2((a c) (b d))
(transpose-array '#2((a b) (c d)) 0 0) => #1(a d)
(transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) =>
                #2((a 4) (b 5) (c 6))

Function: enclose-array array dim0 dim1 ...
dim0, dim1 ... should be nonnegative integers less than the rank of array. enclose-array returns an array resembling an array of shared arrays. The dimensions of each shared array are the same as the dimth dimensions of the original array, the dimensions of the outer array are the same as those of the original array that did not match a dim.

An enclosed array is not a general Scheme array. Its elements may not be set using array-set!. Two references to the same element of an enclosed array will be equal? but will not in general be eq?. The value returned by array-prototype when given an enclosed array is unspecified.

examples:

(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) =>
   #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>

(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) =>
   #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>

Function: array-shape array
Returns a list of inclusive bounds of integers.
(array-shape (make-array 'foo '(-1 3) 5)) => ((-1 3) (0 4))

Function: array-dimensions array
Array-dimensions is similar to array-shape but replaces elements with a 0 minimum with one greater than the maximum. So:
(array-dimensions (make-array 'foo '(-1 3) 5)) => ((-1 3) 5)

Function: array-rank obj
Returns the number of dimensions of obj. If obj is not an array, 0 is returned.

Function: array->list array
Returns a list consisting of all the elements, in order, of array.

Function: array-copy! source destination
Copies every element from vector or array source to the corresponding element of destination. destination must have the same rank as source, and be at least as large in each dimension. The order of copying is unspecified.

Function: serial-array-copy! source destination
Same as array-copy! but guaranteed to copy in row-major order.

Function: array-fill! array fill
Stores fill in every element of array. The value returned is unspecified.

Function: array-equal? array0 array1 ...
Returns #t iff all arguments are arrays with the same shape, the same type, and have corresponding elements which are either equal? or array-equal?. This function differs from equal? in that a one dimensional shared array may be array-equal? but not equal? to a vector or uniform vector.

Function: array-contents array
Function: array-contents array strict
If array may be unrolled into a one dimensional shared array without changing their order (last subscript changing fastest), then array-contents returns that shared array, otherwise it returns #f. All arrays made by make-array and make-uniform-array may be unrolled, some arrays made by make-shared-array may not be.

If the optional argument strict is provided, a shared array will be returned only if its elements are stored internally contiguous in memory.

Array Mapping

(require 'array-for-each)

Function: array-map! array0 proc array1 ...

If array1, ... are arrays, they must have the same number of dimensions as array0 and have a range for each index which includes the range for the corresponding index in array0. If they are scalars, that is, not arrays, vectors, or strings, then they will be converted internally to arrays of the appropriate shape. proc is applied to each tuple of elements of array1 ... and the result is stored as the corresponding element in array0. The value returned is unspecified. The order of application is unspecified.

Function: serial-array-map! array0 proc array1 ...
Same as array-map!, but guaranteed to apply proc in row-major order.

Function: array-for-each proc array0 ...
proc is applied to each tuple of elements of array0 ... in row-major order. The value returned is unspecified.

Function: array-index-map! array proc
applies proc to the indices of each element of array in turn, storing the result in the corresponding element. The value returned and the order of application are unspecified.

One can implement array-indexes as

(define (array-indexes array)
    (let ((ra (apply make-array #f (array-shape array))))
      (array-index-map! ra (lambda x x))
      ra))

Another example:

(define (apl:index-generator n)
    (let ((v (make-uniform-vector n 1)))
      (array-index-map! v (lambda (i) i))
      v))

Function: scalar->array scalar array prototype
Returns a uniform array of the same shape as array, having only one shared element, which is eqv? to scalar. If the optional argument prototype is supplied it will be used as the prototype for the returned array. Otherwise the returned array will be of the same type as array if that is possible, and a conventional array if it is not. This function is used internally by array-map! and friends to handle scalar arguments.

Uniform Array

Uniform Arrays and vectors are arrays whose elements are all of the same type. Uniform vectors occupy less storage than conventional vectors. Uniform Array procedures also work on vectors, uniform-vectors, bit-vectors, and strings.

prototype arguments in the following procedures are interpreted according to the table:

prototype       type                             display prefix

#t              boolean (bit-vector)                    #b
#\a             char (string)                           #a
integer >0      unsigned integer                        #u
integer <0      signed integer                          #e
1.0             float (single precision)                #s
1/3             double (double precision float)         #i
+i              complex (double precision)              #c
()              conventional vector                     #

Unshared uniform character 0-based arrays of rank 1 (dimension) are equivalent to (and can't be distinguished from) strings.

(make-uniform-array #\a 3) => "$q2"

Unshared uniform boolean 0-based arrays of rank 1 (dimension) are equivalent to (and can't be distinguished from) section Bit Vectors.

(make-uniform-array #t 3) => #*000
==
#b(#f #f #f) => #*000
==
#1b(#f #f #f) => #*000

Other uniform vectors are written in a form similar to that of vectors, except that a single character from the above table is put between # and (. For example, '#e(3 5 9) returns a uniform vector of signed integers.

Function: uniform-vector-ref uve index
Returns the element at the index element in uve.

Function: uniform-vector-set! uve index new-value
Sets the element at the index element in uve to new-value. The value returned by uniform-vector-set! is unspecified.

Function: array? obj prototype
Returns #t if the obj is an array of type corresponding to prototype, and #f if not.

Function: make-uniform-array prototype bound1 bound2 ...
Creates and returns a uniform array of type corresponding to prototype that has as many dimensions as there are bounds.

Function: array-prototype array
Returns an object that would produce an array of the same type as array, if used as the prototype for make-uniform-array.

Function: list->uniform-array rank prot lst
Function: list->uniform-vector prot lst
Returns a uniform array of the type indicated by prototype prot with elements the same as those of lst. Elements must be of the appropriate type, no coercions are done.

Function: uniform-vector-fill! uve fill
Stores fill in every element of uve. The value returned is unspecified.

Function: uniform-vector-length uve
Returns the number of elements in uve.

Function: dimensions->uniform-array dims prototype fill
Function: dimensions->uniform-array dims prototype
Function: make-uniform-vector length prototype fill
Function: make-uniform-vector length prototype
Creates and returns a uniform array or vector of type corresponding to prototype with dimensions dims or length length. If the fill argument is supplied, the returned array is filled with this value.

Function: uniform-array-read! ura
Function: uniform-array-read! ura port
Function: uniform-vector-read! uve
Function: uniform-vector-read! uve port
Attempts to read all elements of ura, in lexicographic order, as binary objects from port. If an end of file is encountered during uniform-array-read! the objects up to that point only are put into ura (starting at the beginning) and the remainder of the array is unchanged.

uniform-array-read! returns the number of objects read. port may be omitted, in which case it defaults to the value returned by (current-input-port).

Function: uniform-array-write ura
Function: uniform-array-write ura port
Function: uniform-vector-write uve
Function: uniform-vector-write uve port
Writes all elements of ura as binary objects to port. The number of of objects actually written is returned. port may be omitted, in which case it defaults to the value returned by (current-output-port).

Function: logaref array index1 index2 ...
If an index is provided for each dimension of array returns the index1, index2, ...'th element of array. If one more index is provided, then the last index specifies bit position of the twos-complement representation of the array element indexed by the other indexs returning #t if the bit is 1, and #f if 0. It is an error if this element is not an exact integer.

(logaref '#(#b1101 #b0010) 0)       => #b1101
(logaref '#(#b1101 #b0010) 0 1)     => #f
(logaref '#2((#b1101 #b0010)) 0 0)  => #b1101

Function: logaset! array val index1 index2 ...
If an index is provided for each dimension of array sets the index1, index2, ...'th element of array to val. If one more index is provided, then the last index specifies bit position of the twos-complement representation of an exact integer array element, setting the bit to 1 if bool is #t and to 0 if bool is #f if 0. In this case it is an error if the array element is not an exact integer or if val is not boolean.

Bit Vectors

Bit vectors can be written and read as a sequence of 0s and 1s prefixed by #*.

#b(#f #f #f #t #f #t #f) => #*0001010

Some of these operations will eventually be generalized to other uniform-arrays.

Function: bit-count bool bv
Returns the number occurrences of bool in bv.

Function: bit-position bool bv k
Returns the minimum index of an occurrence of bool in bv which is at least k. If no bool occurs within the specified range #f is returned.

Function: bit-invert! bv
Modifies bv by replacing each element with its negation.

Function: bit-set*! bv uve bool
If uve is a bit-vector bv and uve must be of the same length. If bool is #t, uve is OR'ed into bv; If bool is #f, the inversion of uve is AND'ed into bv.

If uve is a unsigned integer vector all the elements of uve must be between 0 and the LENGTH of bv. The bits of bv corresponding to the indexes in uve are set to bool.

The return value is unspecified.

Function: bit-count* bv uve bool
Returns
(bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).

bv is not modified.

I/O-Extensions

If 'i/o-extensions is provided (by linking in `ioext.o'), section `Line I/O' in SLIB, and the following functions are defined:

Function: stat <port-or-string>
Returns a vector of integers describing the argument. The argument can be either a string or an open input port. If the argument is an open port then the returned vector describes the file to which the port is opened; If the argument is a string then the returned vector describes the file named by that string. If there exists no file with the name string, or if the file cannot be accessed #f is returned. The elements of the returned vector are as follows:

0 st_dev
ID of device containing a directory entry for this file
1 st_ino
Inode number
2 st_mode
File type, attributes, and access control summary
3 st_nlink
Number of links
4 st_uid
User ID of file owner
5 st_gid
Group ID of file group
6 st_rdev
Device ID; this entry defined only for char or blk spec files
7 st_size
File size (bytes)
8 st_atime
Time of last access
9 st_mtime
Last modification time
10 st_ctime
Last file status change time

Function: getpid
Returns the process ID of the current process.

Function: file-position port
Returns the current position of the character in port which will next be read or written. If port is not open to a file the result is unspecified.

Function: file-set-position port integer
Sets the current position in port which will next be read or written. If port is not open to a file the action of file-set-position is unspecified. The result of file-set-position is unspecified.

Function: reopen-file filename modes port
Closes port port and reopens it with filename and modes. reopen-file returns #t if successful, #f if not.

Function: duplicate-port port modes
Creates and returns a duplicate port from port. Duplicate unbuffered ports share one file position. modes are as for section Files and Ports.

Function: redirect-port! from-port to-port
Closes to-port and makes to-port be a duplicate of from-port. redirect-port! returns to-port if successful, #f if not. If unsuccessful, to-port is not closed.

Function: opendir dirname
Returns a directory object corresponding to the file system directory named dirname. If unsuccessful, returns #f.

Function: readdir dir
Returns the string name of the next entry from the directory dir. If there are no more entries in the directory, readdir returns a #f.

Function: rewinddir dir
Reinitializes dir so that the next call to readdir with dir will return the first entry in the directory again.

Function: closedir dir
Closes dir and returns #t. If dir is already closed,, closedir returns a #f.

Function: directory-for-each proc directory
The lists must be lists, and proc must be a procedure taking one argument. `Directory-For-Each' applies proc to the (string) name of each file in directory. The dynamic order in which proc is applied to the elements of the lists is unspecified. The value returned by `directory-for-each' is unspecified.

Function: directory-for-each proc directory pred
Applies proc only to those filenames for which the procedure pred returns a non-false value.

Function: directory-for-each proc directory match
Applies proc only to those filenames for which (filename:match?? match) would return a non-false value (see section `Filenames' in SLIB).

(require 'directory-for-each)
(directory-for-each print "." "[A-Z]*.scm")
-|
"Init.scm" 
"Iedline.scm" 
"Link.scm" 
"Macro.scm" 
"Transcen.scm" 
"Init5c4.scm" 

Function: mkdir path mode
The mkdir function creates a new, empty directory whose name is path. The integer argument mode specifies the file permissions for the new directory. See section `The Mode Bits for Access Permission' in Gnu C Library, for more information about this.

mkdir returns if successful, #f if not.

Function: rmdir path
The rmdir function deletes the directory path. The directory must be empty before it can be removed. rmdir returns if successful, #f if not.

Function: chdir filename
Changes the current directory to filename. If filename does not exist or is not a directory, #f is returned. Otherwise, #t is returned.

Function: getcwd
The function getcwd returns a string containing the absolute file name representing the current working directory. If this string cannot be obtained, #f is returned.

Function: rename-file oldfilename newfilename
Renames the file specified by oldfilename to newfilename. If the renaming is successful, #t is returned. Otherwise, #f is returned.

Function: chmod file mode
The function chmod sets the access permission bits for the file named by file to mode. The file argument may be a string containing the filename or a port open to the file.

chmod returns if successful, #f if not.

Function: utime pathname acctime modtime
Sets the file times associated with the file named pathname to have access time acctime and modification time modtime. utime returns if successful, #f if not.

Function: umask mode
The function umask sets the file creation mask of the current process to mask, and returns the previous value of the file creation mask.

Function: fileno port
Returns the integer file descriptor associated with the port port. If an error is detected, #f is returned.

Function: access pathname how
Returns #t if the file named by pathname can be accessed in the way specified by the how argument. The how argument can be the logior of the flags:

  1. File-exists?
  2. File-is-executable?
  3. File-is-writable?
  1. File-is-readable?

Or the how argument can be a string of 0 to 3 of the following characters in any order. The test performed is the and of the associated tests and file-exists?.

x
File-is-executable?
w
File-is-writable?
r
File-is-readable?

Function: execl command arg0 ...
Function: execlp command arg0 ...
Transfers control to program command called with arguments arg0 .... For execl, command must be an exact pathname of an executable file. execlp searches for command in the list of directories specified by the environment variable PATH. The convention is that arg0 is the same name as command.

If successful, this procedure does not return. Otherwise an error message is printed and the integer errno is returned.

Function: execv command arglist
Function: execvp command arglist
Like execl and execlp except that the set of arguments to command is arglist.

Function: putenv string
adds or removes definitions from the environment. If the string is of the form `NAME=VALUE', the definition is added to the environment. Otherwise, the string is interpreted as the name of an environment variable, and any definition for this variable in the environment is removed.

Names of environment variables are case-sensitive and must not contain the character =. System-defined environment variables are invariably uppercase.

Putenv is used to set up the environment before calls to execl, execlp, execv, execvp, system, or open-pipe (see section I/O-Extensions).

To access environment variables, use getenv (see section `System Interface' in SLIB).

Posix Extensions

If 'posix is provided (by linking in `posix.o'), the following functions are defined:

Function: open-pipe string modes
If the string modes contains an r, returns an input port capable of delivering characters from the standard output of the system command string. Otherwise, returns an output port capable of receiving characters which become the standard input of the system command string. If a pipe cannot be created #f is returned.

Function: open-input-pipe string
Returns an input port capable of delivering characters from the standard output of the system command string. If a pipe cannot be created #f is returned.

Function: open-output-pipe string
Returns an output port capable of receiving characters which become the standard input of the system command string. If a pipe cannot be created #f is returned.

Function: close-port pipe
Closes the pipe, rendering it incapable of delivering or accepting characters. This routine has no effect if the pipe has already been closed. The value returned is unspecified.

Function: pipe
Returns (cons rd wd) where rd and wd are the read and write (port) ends of a pipe respectively.

Function: fork
Creates a copy of the process calling fork. Both processes return from fork, but the calling (parent) process's fork returns the child process's ID whereas the child process's fork returns 0.

For a discussion of IDs See section `Process Persona' in libc.

Function: getppid
Returns the process ID of the parent of the current process. For a process's own ID See section I/O-Extensions.

Function: getuid
Returns the real user ID of this process.

Function: getgid
Returns the real group ID of this process.

Function: getegid
Returns the effective group ID of this process.

Function: geteuid
Returns the effective user ID of this process.

Function: setuid id
Sets the real user ID of this process to id. Returns #t if successful, #f if not.

Function: setgid id
Sets the real group ID of this process to id. Returns #t if successful, #f if not.

Function: setegid id
Sets the effective group ID of this process to id. Returns #t if successful, #f if not.

Function: seteuid id
Sets the effective user ID of this process to id. Returns #t if successful, #f if not.

Function: kill pid sig
The kill function sends the signal signum to the process or process group specified by pid. Besides the signals listed in section `Standard Signals' in GNU C Library, signum can also have a value of zero to check the validity of the pid.

The pid specifies the process or process group to receive the signal:

> 0
The process whose identifier is pid.
0
All processes in the same process group as the sender. The sender itself does not receive the signal.
-1
If the process is privileged, send the signal to all processes except for some special system processes. Otherwise, send the signal to all processes with the same effective user ID.
< -1
The process group whose identifier is (abs pid).

A process can send a signal to itself with (kill (getpid) signum). If kill is used by a process to send a signal to itself, and the signal is not blocked, then kill delivers at least one signal (which might be some other pending unblocked signal instead of the signal signum) to that process before it returns.

The return value from kill is zero if the signal can be sent successfully. Otherwise, no signal is sent, and a value of -1 is returned. If pid specifies sending a signal to several processes, kill succeeds if it can send the signal to at least one of them. There's no way you can tell which of the processes got the signal or whether all of them did.

Function: waitpid pid options

The waitpid function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is deliverd whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called zombie process), the function returns immediately. Any system resources used by the child are freed.

The value of pid can be one of:

< -1
which means to wait for any child process whose process group ID is equal to the absolute value of
-1
which means to wait for any child process whose process group ID is equal to the (abs pid).
-1
which means to wait for any child process; this is the same behaviour which wait exhibits.
0
which means to wait for any child process whose process group ID is equal to that of the calling process.
> 0
which means to wait for the child whose process ID is equal to the value of pid.

The value of options is one of the following:

  1. Nothing special.
  2. (WNOHANG) which means to return immediately if no child is there to be waited for.
  3. (WUNTRACED) which means to also return for children which are stopped, and whose status has not been reported.
  4. Which means both of the above.

The return value is normally the process ID of the child process whose status is reported. If the WNOHANG option was specified and no child process is waiting to be noticed, the value is zero. A value of #f is returned in case of error and errno is set. For information about the errno codes See section `Process Completion' in libc.

Function: uname
You can use the uname procedure to find out some information about the type of computer your program is running on.

Returns a vector of strings. These strings are:

  1. The name of the operating system in use.
  2. The network name of this particular computer.
  3. The current release level of the operating system implementation.
  4. The current version level within the release of the operating system.
  5. Description of the type of hardware that is in use. Some examples are `"i386-ANYTHING"', `"m68k-hp"', `"sparc-sun"', `"m68k-sun"', `"m68k-sony"' and `"mips-dec"'.

Function: getpw name
Function: getpw uid
Function: getpw
Returns a vector of information for the entry for NAME, UID, or the next entry if no argument is given. The information is:

  1. The user's login name.
  2. The encrypted password string.
  3. The user ID number.
  4. The user's default group ID number.
  5. A string typically containing the user's real name, and possibly other information such as a phone number.
  6. The user's home directory, initial working directory, or #f, in which case the interpretation is system-dependent.
  7. The user's default shell, the initial program run when the user logs in, or #f, indicating that the system default should be used.

Function: setpwent #t
Rewinds the pw entry table back to the begining.

Function: setpwent #f
Function: setpwent
Closes the pw table.

Function: getgr name
Function: getgr uid
Function: getgr
Returns a vector of information for the entry for NAME, UID, or the next entry if no argument is given. The information is:

  1. The name of the group.
  2. The encrypted password string.
  3. The group ID number.
  4. A list of (string) names of users in the group.

Function: setgrent #t
Rewinds the group entry table back to the begining.

Function: setgrent #f
Function: setgrent
Closes the group table.

Function: getgroups
Returns a vector of all the supplementary group IDs of the process.

Function: link oldname newname
The link function makes a new link to the existing file named by oldname, under the new name newname.

link returns a value of #t if it is successful and #f on failure.

Function: chown filename owner group
The chown function changes the owner of the file filename to owner, and its group owner to group.

chown returns a value of #t if it is successful and #f on failure.

Function: ttyname port
If port port is associated with a terminal device, returns a string containing the file name of termainal device; otherwise #f.

Unix Extensions

If 'unix is provided (by linking in `unix.o'), the following functions are defined:

These priveledged and symbolic link functions are not in Posix:

Function: symlink oldname newname
The symlink function makes a symbolic link to oldname named newname.

symlink returns a value of #t if it is successful and #f on failure.

Function: readlink filename
Returns the value of the symbolic link filename or #f for failure.

Function: lstat filename
The lstat function is like stat, except that it does not follow symbolic links. If filename is the name of a symbolic link, lstat returns information about the link itself; otherwise, lstat works like stat. See section I/O-Extensions.

Function: nice increment
Increment the priority of the current process by increment. chown returns a value of #t if it is successful and #f on failure.

Function: acct filename
When called with the name of an exisitng file as argument, accounting is turned on, records for each terminating pro-cess are appended to filename as it terminates. An argument of #f causes accounting to be turned off.

acct returns a value of #t if it is successful and #f on failure.

Function: mknod filename mode dev
The mknod function makes a special file with name filename and modes mode for device number dev.

mknod returns a value of #t if it is successful and #f on failure.

Function: sync
sync first commits inodes to buffers, and then buffers to disk. sync() only schedules the writes, so it may return before the actual writing is done. The value returned is unspecified.

Regular Expression Pattern Matching

These functions are defined in `rgx.c' using a POSIX or GNU regex library. If your computer does not support regex, a package is available via ftp from `prep.ai.mit.edu:/pub/gnu/regex-0.12.tar.gz'. For a description of regular expressions, See section `syntax' in "regex" regular expression matching library.

Function: regcomp pattern [flags]
Compile a regular expression. Return a compiled regular expression, or an integer error code suitable as an argument to regerror.

flags in regcomp is a string of option letters used to control the compilation of the regular expression. The letters may consist of:

`n'
newlines won't be matched by . or hat lists; ( [^...] )
`i'
ignore case. only when compiled with _GNU_SOURCE:
`0'
allows dot to match a null character.
`f'
enable GNU fastmaps.

Function: regerror errno
Returns a string describing the integer errno returned when regcomp fails.

Function: regexec re string
Returns #f or a vector of integers. These integers are in doublets. The first of each doublet is the index of string of the start of the matching expression or sub-expression (delimited by parentheses in the pattern). The last of each doublet is index of string of the end of that expression. #f is returned if the string does not match.

Function: regmatch? re string
Returns #t if the pattern such that regexp = (regcomp pattern) matches string as a POSIX extended regular expressions. Returns #f otherwise.

Function: regsearch re string [start [len]]
Function: regsearchv re string [start [len]]
Function: regmatch re string [start [len]]
Function: regmatchv re string [start [len]]
Regsearch searches for the pattern within the string.

Regmatch anchors the pattern and begins matching it against string.

Regsearch returns the character position where re starts, or #f if not found.

Regmatch returns the number of characters matched, #f if not matched.

Regsearchv and regmatchv return the match vector is returned if re is found, #f otherwise.

re
may be either:
  1. a compiled regular expression returned by regcomp;
  2. a string representing a regular expression;
  3. a list of a string and a set of option letters.
string
The string to be operated upon.
start
The character position at which to begin the search or match. If absent, the default is zero. Compiled _GNU_SOURCE and using GNU libregex only: When searching, if start is negative, the absolute value of start will be used as the start location and reverse searching will be performed.
len
The search is allowed to examine only the first len characters of string. If absent, the entire string may be examined.

Function: string-split re string
Function: string-splitv re string
String-split splits a string into substrings that are separated by re, returning a vector of substrings.

String-splitv returns a vector of string positions that indicate where the substrings are located.

Function: string-edit re edit-spec string [count]
Returns the edited string.

edit-spec
Is a string used to replace occurances of re. Backquoted integers in the range of 1-9 may be used to insert subexpressions in re, as in sed.
count
The number of substitutions for string-edit to perform. If #t, all occurances of re will be replaced. The default is to perform one substitution.

Line Editing

These procedures provide input line editing and recall.

These functions are defined in `edline.c' and `Iedline.scm' using the editline or GNU readline (see section `Overview' in GNU Readline Library) libraries available from:

When `Iedline.scm' is loaded, if the current input port is the default input port and the environment variable EMACS is not defined, line-editing mode will be entered.

Function: default-input-port
Returns the initial current-input-port SCM was invoked with (stdin).

Function: default-output-port
Returns the initial current-output-port SCM was invoked with (stdout).

Function: make-edited-line-port
Returns an input/output port that allows command line editing and retrieval of history.

Function: line-editing
Returns the current edited line port or #f.

Function: line-editing bool
If bool is false, exits line-editing mode and returns the previous value of (line-editing). If bool is true, sets the current input and output ports to an edited line port and returns the previous value of (line-editing).

Curses

These functions are defined in `crs.c' using the curses library. Unless otherwise noted these routines return #t for successful completion and #f for failure.

Function: initscr
Returns a port for a full screen window. This routine must be called to initialize curses.

Function: endwin
A program should call endwin before exiting or escaping from curses mode temporarily, to do a system call, for example. This routine will restore termio modes, move the cursor to the lower left corner of the screen and reset the terminal into the proper non-visual mode. To resume after a temporary escape, call section Window Manipulation.

Output Options Setting

These routines set options within curses that deal with output. All options are initially #f, unless otherwise stated. It is not necessary to turn these options off before calling endwin.

Function: clearok win bf
If enabled (bf is #t), the next call to force-output or refresh with win will clear the screen completely and redraw the entire screen from scratch. This is useful when the contents of the screen are uncertain, or in some cases for a more pleasing visual effect.

Function: idlok win bf
If enabled (bf is #t), curses will consider using the hardware "insert/delete-line" feature of terminals so equipped. If disabled (bf is #f), curses will very seldom use this feature. The "insert/delete-character" feature is always considered. This option should be enabled only if your application needs "insert/delete-line", for example, for a screen editor. It is disabled by default because

"insert/delete-line" tends to be visually annoying when used in applications where it is not really needed. If "insert/delete-line" cannot be used, curses will redraw the changed portions of all lines.

Function: leaveok win bf
Normally, the hardware cursor is left at the location of the window cursor being refreshed. This option allows the cursor to be left wherever the update happens to leave it. It is useful for applications where the cursor is not used, since it reduces the need for cursor motions. If possible, the cursor is made invisible when this option is enabled.

Function: scrollok win bf
This option controls what happens when the cursor of window win is moved off the edge of the window or scrolling region, either from a newline on the bottom line, or typing the last character of the last line. If disabled (bf is #f), the cursor is left on the bottom line at the location where the offending character was entered. If enabled (bf is #t), force-output is called on the window win, and then the physical terminal and window win are scrolled up one line.

Note: in order to get the physical scrolling effect on the terminal, it is also necessary to call idlok.

Function: nodelay win bf
This option causes wgetch to be a non-blocking call. If no input is ready, wgetch will return an eof-object. If disabled, wgetch will hang until a key is pressed.

Terminal Mode Setting

These routines set options within curses that deal with input. The options involve using ioctl(2) and therefore interact with curses routines. It is not necessary to turn these options off before calling endwin. The routines in this section all return an unspecified value.

Function: cbreak
Function: nocbreak
These two routines put the terminal into and out of CBREAK mode, respectively. In CBREAK mode, characters typed by the user are immediately available to the program and erase/kill character processing is not performed. When in NOCBREAK mode, the tty driver will buffer characters typed until a LFD or RET is typed. Interrupt and flowcontrol characters are unaffected by this mode. Initially the terminal may or may not be in CBREAK mode, as it is inherited, therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses will set CBREAK mode.

Note: cbreak overrides raw. For a discussion of how these routines interact with echo and noecho See section Input.

Function: raw
Function: noraw
The terminal is placed into or out of RAW mode. RAW mode is similar to CBREAK mode, in that characters typed are immediately passed through to the user program. The differences are that in RAW mode, the interrupt, quit, suspend, and flow control characters are passed through uninterpreted, instead of generating a signal. RAW mode also causes 8-bit input and output. The behavior of the BREAK key depends on other bits in the terminal driver that are not set by curses.

Function: echo
Function: noecho
These routines control whether characters typed by the user are echoed by read-char as they are typed. Echoing by the tty driver is always disabled, but initially read-char is in ECHO mode, so characters typed are echoed. Authors of most interactive programs prefer to do their own echoing in a controlled area of the screen, or not to echo at all, so they disable echoing by calling noecho. For a discussion of how these routines interact with echo and noecho See section Input.

Function: nl
Function: nonl
These routines control whether LFD is translated into RET and LFD on output, and whether RET is translated into LFD on input. Initially, the translations do occur. By disabling these translations using nonl, curses is able to make better use of the linefeed capability, resulting in faster cursor motion.

Function: resetty
Function: savetty
These routines save and restore the state of the terminal modes. savetty saves the current state of the terminal in a buffer and resetty restores the state to what it was at the last call to savetty.

Window Manipulation

Function: newwin nlines ncols begy begx
Create and return a new window with the given number of lines (or rows), nlines, and columns, ncols. The upper left corner of the window is at line begy, column begx. If either nlines or ncols is 0, they will be set to the value of LINES-begy and COLS-begx. A new full-screen window is created by calling newwin(0,0,0,0).

Function: subwin orig nlines ncols begy begx
Create and return a pointer to a new window with the given number of lines (or rows), nlines, and columns, ncols. The window is at position (begy, begx) on the screen. This position is relative to the screen, and not to the window orig. The window is made in the middle of the window orig, so that changes made to one window will affect both windows. When using this routine, often it will be necessary to call touchwin or touchline on orig before calling force-output.

Function: close-port win
Deletes the window win, freeing up all memory associated with it. In the case of sub-windows, they should be deleted before the main window win.

Function: refresh
Function: force-output win
These routines are called to write output to the terminal, as most other routines merely manipulate data structures. force-output copies the window win to the physical terminal screen, taking into account what is already there in order to minimize the amount of information that's sent to the terminal (called optimization). Unless leaveok has been enabled, the physical cursor of the terminal is left at the location of window win's cursor. With refresh, the number of characters output to the terminal is returned.

Function: mvwin win y x
Move the window win so that the upper left corner will be at position (y, x). If the move would cause the window win to be off the screen, it is an error and the window win is not moved.

Function: overlay srcwin dstwin
Function: overwrite srcwin dstwin

These routines overlay srcwin on top of dstwin; that is, all text in srcwin is copied into dstwin. srcwin and dstwin need not be the same size; only text where the two windows overlap is copied. The difference is that overlay is non-destructive (blanks are not copied), while overwrite is destructive.

Function: touchwin win
Function: touchline win start count
Throw away all optimization information about which parts of the window win have been touched, by pretending that the entire window win has been drawn on. This is sometimes necessary when using overlapping windows, since a change to one window will affect the other window, but the records of which lines have been changed in the other window will not reflect the change. touchline only pretends that count lines have been changed, beginning with line start.

Function: wmove win y x
The cursor associated with the window win is moved to line (row) y, column x. This does not move the physical cursor of the terminal until refresh (or force-output) is called. The position specified is relative to the upper left corner of the window win, which is (0, 0).

Output

These routines are used to draw text on windows

Function: display ch win
Function: display str win
Function: wadd win ch
Function: wadd win str
The character ch or characters in str are put into the window win at the current cursor position of the window and the position of win's cursor is advanced. At the right margin, an automatic newline is performed. At the bottom of the scrolling region, if scrollok is enabled, the scrolling region will be scrolled up one line.

If ch is a TAB, LFD, or backspace, the cursor will be moved appropriately within the window win. A LFD also does a wclrtoeol before moving. TAB characters are considered to be at every eighth column. If ch is another control character, it will be drawn in the C-x notation. (Calling winch after adding a control character will not return the control character, but instead will return the representation of the control character.)

Video attributes can be combined with a character by or-ing them into the parameter. This will result in these attributes also being set. The intent here is that text, including attributes, can be copied from one place to another using inch and display. See standout, below.

Note: For wadd ch can be an integer and will insert the character of the corresponding value.

Function: werase win
This routine copies blanks to every position in the window win.

Function: wclear win
This routine is like werase, but it also calls section Output Options Setting, arranging that the screen will be cleared completely on the next call to refresh or force-output for window win, and repainted from scratch.

Function: wclrtobot win
All lines below the cursor in window win are erased. Also, the current line to the right of the cursor, inclusive, is erased.

Function: wclrtoeol win
The current line to the right of the cursor, inclusive, is erased.

Function: wdelch win
The character under the cursor in the window win is deleted. All characters to the right on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. This does not imply use of the hardware "delete-character" feature.

Function: wdeleteln win
The line under the cursor in the window win is deleted. All lines below the current line are moved up one line. The bottom line win is cleared. The cursor position does not change. This does not imply use of the hardware "deleteline" feature.

Function: winsch win ch
The character ch is inserted before the character under the cursor. All characters to the right are moved one SPC to the right, possibly losing the rightmost character of the line. The cursor position does not change . This does not imply use of the hardware "insertcharacter" feature.

Function: winsertln win
A blank line is inserted above the current line and the bottom line is lost. This does not imply use of the hardware "insert-line" feature.

Function: scroll win
The window win is scrolled up one line. This involves moving the lines in win's data structure. As an optimization, if win is stdscr and the scrolling region is the entire window, the physical screen will be scrolled at the same time.

Input

Function: read-char win
A character is read from the terminal associated with the window win. Depending on the setting of cbreak, this will be after one character (CBREAK mode), or after the first newline (NOCBREAK mode). Unless noecho has been set, the character will also be echoed into win.

When using read-char, do not set both NOCBREAK mode (nocbreak) and ECHO mode (echo) at the same time. Depending on the state of the terminal driver when each character is typed, the program may produce undesirable results.

Function: winch win
The character, of type chtype, at the current position in window win is returned. If any attributes are set for that position, their values will be OR'ed into the value returned.

Function: getyx win
A list of the y and x coordinates of the cursor position of the window win is returned

Curses Miscellany

Function: wstandout win
Function: wstandend win

These functions set the current attributes of the window win. The current attributes of win are applied to all characters that are written into it. Attributes are a property of the character, and move with the character through any scrolling and insert/delete line/character operations. To the extent possible on the particular terminal, they will be displayed as the graphic rendition of characters put on the screen.

wstandout sets the current attributes of the window win to be visibly different from other text. wstandend turns off the attributes.

Function: box win vertch horch
A box is drawn around the edge of the window win. vertch and horch are the characters the box is to be drawn with. If vertch and horch are 0, then appropriate default characters, ACS_VLINE and ACS_HLINE, will be used.

Note: vertch and horch can be an integers and will insert the character (with attributes) of the corresponding values.

Function: unctrl c
This macro expands to a character string which is a printable representation of the character c. Control characters are displayed in the C-x notation. Printing characters are displayed as is.

Sockets

These procedures (defined in `socket.c') provide a Scheme interface to most of the C socket library. For more information on sockets, See section `Sockets' in The GNU C Library Reference Manual.

Host Data, Network, Protocol, and Service Inquiries

Constant: af_inet
Constant: af_unix
Integer family codes for Internet and Unix sockets, respectively.

Function: gethost host-spec
Function: gethost
Returns a vector of information for the entry for HOST-SPEC or the next entry if HOST-SPEC isn't given. The information is:

  1. host name string
  2. list of host aliases strings
  3. integer address type (AF_INET)
  4. integer size of address entries (in bytes)
  5. list of integer addresses

Function: sethostent stay-open
Function: sethostent
Rewinds the host entry table back to the begining if given an argument. If the argument stay-open is #f queries will be be done using UDP datagrams. Otherwise, a connected TCP socket will be used. When called without an argument, the host table is closed.

Function: getnet name-or-number
Function: getnet
Returns a vector of information for the entry for name-or-number or the next entry if an argument isn't given. The information is:

  1. official network name string
  2. list of network aliases strings
  3. integer network address type (AF_INET)
  4. integer network number

Function: setnetent stay-open
Function: setnetent
Rewinds the network entry table back to the begining if given an argument. If the argument stay-open is #f the table will be closed between calls to getnet. Otherwise, the table stays open. When called without an argument, the network table is closed.

Function: getproto name-or-number
Function: getproto
Returns a vector of information for the entry for name-or-number or the next entry if an argument isn't given. The information is:

  1. official protocol name string
  2. list of protocol aliases strings
  3. integer protocol number

Function: setprotoent stay-open
Function: setprotoent
Rewinds the protocol entry table back to the begining if given an argument. If the argument stay-open is #f the table will be closed between calls to getproto. Otherwise, the table stays open. When called without an argument, the protocol table is closed.

Function: getserv name-or-port-number protocol
Function: getserv
Returns a vector of information for the entry for name-or-port-number and protocol or the next entry if arguments aren't given. The information is:

  1. official service name string
  2. list of service aliases strings
  3. integer port number
  4. protocol

Function: setservent stay-open
Function: setservent
Rewinds the service entry table back to the begining if given an argument. If the argument stay-open is #f the table will be closed between calls to getserv. Otherwise, the table stays open. When called without an argument, the service table is closed.

Internet Addresses and Socket Names

Function: inet:string->address string
Returns the host address number (integer) for host string or #f if not found.

Function: inet:address->string address
Converts an internet (integer) address to a string in numbers and dots notation.

Function: inet:network address
Returns the network number (integer) specified from address or #f if not found.

Function: inet:local-network-address address
Returns the integer for the address of address within its local network or #f if not found.

Function: inet:make-address network local-address
Returns the Internet address of local-address in network.

The type socket-name is used for inquiries about open sockets in the following procedures:

Function: getsockname socket
Returns the socket-name of socket. Returns #f if unsuccessful or socket is closed.

Function: getpeername socket
Returns the socket-name of the socket connected to socket. Returns #f if unsuccessful or socket is closed.

Function: socket-name:family socket-name
Returns the integer code for the family of socket-name.

Function: socket-name:port-number socket-name
Returns the integer port number of socket-name.

Function: socket-name:address socket-name
Returns the integer Internet address for socket-name.

Socket

When a port is returned from one of these calls it is unbuffered. This allows both reading and writing to the same port to work. If you want buffered ports you can (assuming sock-port is a socket i/o port):

(require 'i/o-extensions)
(define i-port (duplicate-port sock-port "r"))
(define o-port (duplicate-port sock-port "w"))

Function: make-stream-socket family
Function: make-stream-socket family protocol

Returns a SOCK_STREAM socket of type family using protocol. If family has the value AF_INET, SO_REUSEADDR will be set. The integer argument protocol corresponds to the integer protocol numbers returned (as vector elements) from (getproto). If the protocol argument is not supplied, the default (0) for the specified family is used. SCM sockets look like ports opened for neither reading nor writing.

Function: make-stream-socketpair family
Function: make-stream-socketpair family protocol

Returns a pair (cons) of connected SOCK_STREAM (socket) ports of type family using protocol. Many systems support only socketpairs of the af-unix family. The integer argument protocol corresponds to the integer protocol numbers returned (as vector elements) from (getproto). If the protocol argument is not supplied, the default (0) for the specified family is used.

Function: socket:shutdown socket how
Makes socket no longer respond to some or all operations depending on the integer argument how:

  1. Further input is disallowed.
  2. Further output is disallowed.
  3. Further input or output is disallowed.

Socket:shutdown returns socket if successful, #f if not.

Function: socket:connect inet-socket host-number port-number
Function: socket:connect unix-socket pathname
Returns socket (changed to a read/write port) connected to the Internet socket on host host-number, port port-number or the Unix socket specified by pathname. Returns #f if not successful.

Function: socket:bind inet-socket port-number
Function: socket:bind unix-socket pathname
Returns inet-socket bound to the integer port-number or the unix-socket bound to new socket in the file system at location pathname. Returns #f if not successful. Binding a unix-socket creates a socket in the file system that must be deleted by the caller when it is no longer needed (using delete-file).

Function: socket:listen socket backlog
The bound (see section Socket) socket is readied to accept connections. The positive integer backlog specifies how many pending connections will be allowed before further connection requests are refused. Returns socket (changed to a read-only port) if successful, #f if not.

Function: char-ready? listen-socket
The input port returned by a successful call to socket:listen can be polled for connections by char-ready? (see section Files and Ports). This avoids blocking on connections by socket:accept.

Function: socket:accept socket
Accepts a connection on a bound, listening socket. Returns an input/output port for the connection.

The following example is not too complicated, yet shows the use of sockets for multiple connections without input blocking.

;;;; Scheme chat server

;;; This program implements a simple `chat' server which accepts
;;; connections from multiple clients, and sends to all clients any
;;; characters received from any client.

;;; To connect to chat `telnet localhost 8001'

(require 'socket)
(require 'i/o-extensions)

(let ((listener-socket (socket:bind (make-stream-socket af_inet) 8001))
      (connections '()))
  (socket:listen listener-socket 5)
  (do () (#f)
    (cond ((char-ready? listener-socket)
           (let ((con (socket:accept listener-socket)))
             (display "accepting connection from ")
             (display (getpeername con))
             (newline)
             (set! connections (cons con connections))
             (display "connected" con)
             (newline con))))
    (set! connections
          (let next ((con-list connections))
            (cond ((null? con-list) '())
                  (else
                   (let ((con (car con-list)))
                     (cond ((char-ready? con)
                            (let ((c (read-char con)))
                              (cond ((eof-object? c)
                                     (display "closing connection from ")
                                     (display (getpeername con))
                                     (newline)
                                     (close-port con)
                                     (next (cdr con-list)))
                                    (else
                                     (for-each (lambda (con)
                                                 (file-set-position con 0)
                                                 (write-char c con)
                                                 (file-set-position con 0))
                                               connections)
                                     (cons con (next (cdr con-list)))))))
                           (else (cons con (next (cdr con-list))))))))))))

You can use `telnet localhost 8001' to connect to the chat server, or you can use a client written in scheme:

;;;; Scheme chat client

;;; this program connects to socket 8001.  It then sends all
;;; characters from current-input-port to the socket and sends all
;;; characters from the socket to current-output-port.

(require 'socket)
(require 'i/o-extensions)

(define con (make-stream-socket af_inet))
(set! con (socket:connect con (inet:string->address "localhost") 8001))

(do ((cs #f (and (char-ready? con) (read-char con)))
     (ct #f (and (char-ready?) (read-char))))
    ((or (eof-object? cs) (eof-object? ct))
     (close-port con))
  (cond (cs (display cs)))
  (cond (ct (file-set-position con 0)
            (display ct con)
            (file-set-position con 0))))


Go to the first, previous, next, last section, table of contents.