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


POSIX System Calls and Networking

POSIX Interface Conventions

These interfaces provide access to operating system facilities. They provide a simple wrapping around the underlying C interfaces to make usage from Scheme more convenient. They are also used to implement the Guile port of section The Scheme shell (scsh).

Generally there is a single procedure for each corresponding Unix facility. There are some exceptions, such as procedures implemented for speed and convenience in Scheme with no primitive Unix equivalent, e.g., copy-file.

The interfaces are intended as far as possible to be portable across different versions of Unix. In some cases procedures which can't be implemented on particular systems may become no-ops, or perform limited actions. In other cases they may throw errors.

General naming conventions are as follows:

Unexpected conditions are generally handled by raising exceptions. There are a few procedures which return a special value if they don't succeed, e.g., getenv returns #f if it the requested string is not found in the environment. These cases are noted in the documentation.

For ways to deal with exceptions, section Exceptions.

Errors which the C-library would report by returning a NULL pointer or through some other means are reported by raising a system-error exception. The value of the Unix errno variable is available in the data passed by the exception.

It can be extracted with the function system-error-errno:

(catch
 'system-error
 (lambda ()
   (mkdir "/this-ought-to-fail-if-I'm-not-root"))
 (lambda stuff
   (let ((errno (system-error-errno stuff)))
     (cond
      ((= errno EACCES)
       (display "You're not allowed to do that."))
      ((= errno EEXIST)
       (display "Already exists."))
      (#t
       (display (strerror errno))))
     (newline))))

Ports and File Descriptors

Conventions generally follow those of scsh, section The Scheme shell (scsh).

File ports are implemented using low-level operating system I/O facilities, with optional buffering to improve efficiency see section File Ports

Note that some procedures (e.g., recv!) will accept ports as arguments, but will actually operate directly on the file descriptor underlying the port. Any port buffering is ignored, including the buffer which implements peek-char and unread-char.

The force-output and drain-input procedures can be used to clear the buffers.

Each open file port has an associated operating system file descriptor. File descriptors are generally not useful in Scheme programs; however they may be needed when interfacing with foreign code and the Unix environment.

A file descriptor can be extracted from a port and a new port can be created from a file descriptor. However a file descriptor is just an integer and the garbage collector doesn't recognize it as a reference to the port. If all other references to the port were dropped, then it's likely that the garbage collector would free the port, with the side-effect of closing the file descriptor prematurely.

To assist the programmer in avoiding this problem, each port has an associated "revealed count" which can be used to keep track of how many times the underlying file descriptor has been stored in other places. If a port's revealed count is greater than zero, the file descriptor will not be closed when the port is garbage collected. A programmer can therefore ensure that the revealed count will be greater than zero if the file descriptor is needed elsewhere.

For the simple case where a file descriptor is "imported" once to become a port, it does not matter if the file descriptor is closed when the port is garbage collected. There is no need to maintain a revealed count. Likewise when "exporting" a file descriptor to the external environment, setting the revealed count is not required provided the port is kept open (i.e., is pointed to by a live Scheme binding) while the file descriptor is in use.

To correspond with traditional Unix behaviour, the three file descriptors (0, 1 and 2) are automatically imported when a program starts up and assigned to the initial values of the current input, output and error ports. The revealed count for each is initially set to one, so that dropping references to one of these ports will not result in its garbage collection: it could be retrieved with fdopen or fdes->ports.

Scheme Procedure: port-revealed port
C Function: scm_port_revealed (port)
Return the revealed count for port.

Scheme Procedure: set-port-revealed! port rcount
C Function: scm_set_port_revealed_x (port, rcount)
Sets the revealed count for a port to a given value. The return value is unspecified.

Scheme Procedure: fileno port
C Function: scm_fileno (port)
Return the integer file descriptor underlying port. Does not change its revealed count.

Scheme Procedure: port->fdes port
Returns the integer file descriptor underlying port. As a side effect the revealed count of port is incremented.

Scheme Procedure: fdopen fdes modes
C Function: scm_fdopen (fdes, modes)
Return a new port based on the file descriptor fdes. Modes are given by the string modes. The revealed count of the port is initialized to zero. The modes string is the same as that accepted by section File Ports.

Scheme Procedure: fdes->ports fd
C Function: scm_fdes_to_ports (fd)
Return a list of existing ports which have fdes as an underlying file descriptor, without changing their revealed counts.

Scheme Procedure: fdes->inport fdes
Returns an existing input port which has fdes as its underlying file descriptor, if one exists, and increments its revealed count. Otherwise, returns a new input port with a revealed count of 1.

Scheme Procedure: fdes->outport fdes
Returns an existing output port which has fdes as its underlying file descriptor, if one exists, and increments its revealed count. Otherwise, returns a new output port with a revealed count of 1.

Scheme Procedure: primitive-move->fdes port fd
C Function: scm_primitive_move_to_fdes (port, fd)
Moves the underlying file descriptor for port to the integer value fdes without changing the revealed count of port. Any other ports already using this descriptor will be automatically shifted to new descriptors and their revealed counts reset to zero. The return value is #f if the file descriptor already had the required value or #t if it was moved.

Scheme Procedure: move->fdes port fdes
Moves the underlying file descriptor for port to the integer value fdes and sets its revealed count to one. Any other ports already using this descriptor will be automatically shifted to new descriptors and their revealed counts reset to zero. The return value is unspecified.

Scheme Procedure: release-port-handle port
Decrements the revealed count for a port.

Scheme Procedure: fsync object
C Function: scm_fsync (object)
Copies any unwritten data for the specified output file descriptor to disk. If port/fd is a port, its buffer is flushed before the underlying file descriptor is fsync'd. The return value is unspecified.

Scheme Procedure: open path flags [mode]
C Function: scm_open (path, flags, mode)
Open the file named by path for reading and/or writing. flags is an integer specifying how the file should be opened. mode is an integer specifying the permission bits of the file, if it needs to be created, before the umask is applied. The default is 666 (Unix itself has no default).

flags can be constructed by combining variables using logior. Basic flags are:

Variable: O_RDONLY
Open the file read-only.
Variable: O_WRONLY
Open the file write-only.
Variable: O_RDWR
Open the file read/write.
Variable: O_APPEND
Append to the file instead of truncating.
Variable: O_CREAT
Create the file if it does not already exist.

See the Unix documentation of the open system call for additional flags.

Scheme Procedure: open-fdes path flags [mode]
C Function: scm_open_fdes (path, flags, mode)
Similar to open but return a file descriptor instead of a port.

Scheme Procedure: close fd_or_port
C Function: scm_close (fd_or_port)
Similar to close-port (see section Closing), but also works on file descriptors. A side effect of closing a file descriptor is that any ports using that file descriptor are moved to a different file descriptor and have their revealed counts set to zero.

Scheme Procedure: close-fdes fd
C Function: scm_close_fdes (fd)
A simple wrapper for the close system call. Close file descriptor fd, which must be an integer. Unlike close (see section Ports and File Descriptors), the file descriptor will be closed even if a port is using it. The return value is unspecified.

Scheme Procedure: unread-char char [port]
C Function: scm_unread_char (char, port)
Place char in port so that it will be read by the next read operation. If called multiple times, the unread characters will be read again in last-in first-out order. If port is not supplied, the current input port is used.

Scheme Procedure: unread-string str port
Place the string str in port so that its characters will be read in subsequent read operations. If called multiple times, the unread characters will be read again in last-in first-out order. If port is not supplied, the current-input-port is used.

Scheme Procedure: pipe
C Function: scm_pipe ()
Return a newly created pipe: a pair of ports which are linked together on the local machine. The car is the input port and the cdr is the output port. Data written (and flushed) to the output port can be read from the input port. Pipes are commonly used for communication with a newly forked child process. The need to flush the output port can be avoided by making it unbuffered using setvbuf.

Writes occur atomically provided the size of the data in bytes is not greater than the value of PIPE_BUF. Note that the output port is likely to block if too much data (typically equal to PIPE_BUF) has been written but not yet read from the input port.

The next group of procedures perform a dup2 system call, if newfd (an integer) is supplied, otherwise a dup. The file descriptor to be duplicated can be supplied as an integer or contained in a port. The type of value returned varies depending on which procedure is used.

All procedures also have the side effect when performing dup2 that any ports using newfd are moved to a different file descriptor and have their revealed counts set to zero.

Scheme Procedure: dup->fdes fd_or_port [fd]
C Function: scm_dup_to_fdes (fd_or_port, fd)
Return a new integer file descriptor referring to the open file designated by fd_or_port, which must be either an open file port or a file descriptor.

Scheme Procedure: dup->inport port/fd [newfd]
Returns a new input port using the new file descriptor.

Scheme Procedure: dup->outport port/fd [newfd]
Returns a new output port using the new file descriptor.

Scheme Procedure: dup port/fd [newfd]
Returns a new port if port/fd is a port, with the same mode as the supplied port, otherwise returns an integer file descriptor.

Scheme Procedure: dup->port port/fd mode [newfd]
Returns a new port using the new file descriptor. mode supplies a mode string for the port (see section File Ports).

Scheme Procedure: duplicate-port port modes
Returns a new port which is opened on a duplicate of the file descriptor underlying port, with mode string modes as for section File Ports. The two ports will share a file position and file status flags.

Unexpected behaviour can result if both ports are subsequently used and the original and/or duplicate ports are buffered. The mode string can include 0 to obtain an unbuffered duplicate port.

This procedure is equivalent to (dup->port port modes).

Scheme Procedure: redirect-port old new
C Function: scm_redirect_port (old, new)
This procedure takes two ports and duplicates the underlying file descriptor from old-port into new-port. The current file descriptor in new-port will be closed. After the redirection the two ports will share a file position and file status flags.

The return value is unspecified.

Unexpected behaviour can result if both ports are subsequently used and the original and/or duplicate ports are buffered.

This procedure does not have any side effects on other ports or revealed counts.

Scheme Procedure: dup2 oldfd newfd
C Function: scm_dup2 (oldfd, newfd)
A simple wrapper for the dup2 system call. Copies the file descriptor oldfd to descriptor number newfd, replacing the previous meaning of newfd. Both oldfd and newfd must be integers. Unlike for dup->fdes or primitive-move->fdes, no attempt is made to move away ports which are using newfd. The return value is unspecified.

Scheme Procedure: port-mode port
Return the port modes associated with the open port port. These will not necessarily be identical to the modes used when the port was opened, since modes such as "append" which are used only during port creation are not retained.

@vgone{close-all-ports-except,1.6}

Scheme Procedure: port-for-each proc
C Function: scm_port_for_each (proc)
Apply proc to each port in the Guile port table in turn. The return value is unspecified. More specifically, proc is applied exactly once to every port that exists in the system at the time port-for-each is invoked. Changes to the port table while port-for-each is running have no effect as far as port-for-each is concerned.

Scheme Procedure: setvbuf port mode [size]
C Function: scm_setvbuf (port, mode, size)
Set the buffering mode for port. mode can be:
_IONBF
non-buffered
_IOLBF
line buffered
_IOFBF
block buffered, using a newly allocated buffer of size bytes. If size is omitted, a default size will be used.

Scheme Procedure: fcntl object cmd [value]
C Function: scm_fcntl (object, cmd, value)
Apply command to the specified file descriptor or the underlying file descriptor of the specified port. value is an optional integer argument.

Values for command are:

F_DUPFD
Duplicate a file descriptor
F_GETFD
Get flags associated with the file descriptor.
F_SETFD
Set flags associated with the file descriptor to value.
F_GETFL
Get flags associated with the open file.
F_SETFL
Set flags associated with the open file to value
F_GETOWN
Get the process ID of a socket's owner, for SIGIO signals.
F_SETOWN
Set the process that owns a socket to value, for SIGIO signals.
FD_CLOEXEC
The value used to indicate the "close on exec" flag with F_GETFL or F_SETFL.

Scheme Procedure: flock file operation
C Function: scm_flock (file, operation)
Apply or remove an advisory lock on an open file. operation specifies the action to be done:
LOCK_SH
Shared lock. More than one process may hold a shared lock for a given file at a given time.
LOCK_EX
Exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.
LOCK_UN
Unlock the file.
LOCK_NB
Don't block when locking. May be specified by bitwise OR'ing it to one of the other operations.

The return value is not specified. file may be an open file descriptor or an open file descriptor port.

Scheme Procedure: select reads writes excepts [secs [usecs]]
C Function: scm_select (reads, writes, excepts, secs, usecs)
This procedure has a variety of uses: waiting for the ability to provide input, accept output, or the existence of exceptional conditions on a collection of ports or file descriptors, or waiting for a timeout to occur. It also returns if interrupted by a signal.

reads, writes and excepts can be lists or vectors, with each member a port or a file descriptor. The value returned is a list of three corresponding lists or vectors containing only the members which meet the specified requirement. The ability of port buffers to provide input or accept output is taken into account. Ordering of the input lists or vectors is not preserved.

The optional arguments secs and usecs specify the timeout. Either secs can be specified alone, as either an integer or a real number, or both secs and usecs can be specified as integers, in which case usecs is an additional timeout expressed in microseconds. If secs is omitted or is #f then select will wait for as long as it takes for one of the other conditions to be satisfied.

The scsh version of select differs as follows: Only vectors are accepted for the first three arguments. The usecs argument is not supported. Multiple values are returned instead of a list. Duplicates in the input vectors appear only once in output. An additional select! interface is provided.

File System

These procedures allow querying and setting file system attributes (such as owner, permissions, sizes and types of files); deleting, copying, renaming and linking files; creating and removing directories and querying their contents; syncing the file system and creating special files.

Scheme Procedure: access? path how
C Function: scm_access (path, how)
Return #t if path corresponds to an existing file and the current process has the type of access specified by how, otherwise #f. how should be specified using the values of the variables listed below. Multiple values can be combined using a bitwise or, in which case #t will only be returned if all accesses are granted.

Permissions are checked using the real id of the current process, not the effective id, although it's the effective id which determines whether the access would actually be granted.

Variable: R_OK
test for read permission.
Variable: W_OK
test for write permission.
Variable: X_OK
test for execute permission.
Variable: F_OK
test for existence of the file.

Scheme Procedure: stat object
C Function: scm_stat (object)
Return an object containing various information about the file determined by obj. obj can be a string containing a file name or a port or integer file descriptor which is open on a file (in which case fstat is used as the underlying system call).

The object returned by stat can be passed as a single parameter to the following procedures, all of which return integers:

stat:dev
The device containing the file.
stat:ino
The file serial number, which distinguishes this file from all other files on the same device.
stat:mode
The mode of the file. This includes file type information and the file permission bits. See stat:type and stat:perms below.
stat:nlink
The number of hard links to the file.
stat:uid
The user ID of the file's owner.
stat:gid
The group ID of the file.
stat:rdev
Device ID; this entry is defined only for character or block special files.
stat:size
The size of a regular file in bytes.
stat:atime
The last access time for the file.
stat:mtime
The last modification time for the file.
stat:ctime
The last modification time for the attributes of the file.
stat:blksize
The optimal block size for reading or writing the file, in bytes.
stat:blocks
The amount of disk space that the file occupies measured in units of 512 byte blocks.

In addition, the following procedures return the information from stat:mode in a more convenient form:

stat:type
A symbol representing the type of file. Possible values are regular, directory, symlink, block-special, char-special, fifo, socket and unknown
stat:perms
An integer representing the access permission bits.

Scheme Procedure: lstat str
C Function: scm_lstat (str)
Similar to stat, but does not follow symbolic links, i.e., it will return information about a symbolic link itself, not the file it points to. path must be a string.

Scheme Procedure: readlink path
C Function: scm_readlink (path)
Return the value of the symbolic link named by path (a string), i.e., the file that the link points to.

Scheme Procedure: chown object owner group
C Function: scm_chown (object, owner, group)
Change the ownership and group of the file referred to by object to the integer values owner and group. object can be a string containing a file name or, if the platform supports fchown, a port or integer file descriptor which is open on the file. The return value is unspecified.

If object is a symbolic link, either the ownership of the link or the ownership of the referenced file will be changed depending on the operating system (lchown is unsupported at present). If owner or group is specified as -1, then that ID is not changed.

Scheme Procedure: chmod object mode
C Function: scm_chmod (object, mode)
Changes the permissions of the file referred to by obj. obj can be a string containing a file name or a port or integer file descriptor which is open on a file (in which case fchmod is used as the underlying system call). mode specifies the new permissions as a decimal number, e.g., (chmod "foo" #o755). The return value is unspecified.

Scheme Procedure: utime pathname [actime [modtime]]
C Function: scm_utime (pathname, actime, modtime)
utime sets the access and modification times for the file named by path. If actime or modtime is not supplied, then the current time is used. actime and modtime must be integer time values as returned by the current-time procedure.
(utime "foo" (- (current-time) 3600))

will set the access time to one hour in the past and the modification time to the current time.

Scheme Procedure: delete-file str
C Function: scm_delete_file (str)
Deletes (or "unlinks") the file specified by path.

Scheme Procedure: copy-file oldfile newfile
C Function: scm_copy_file (oldfile, newfile)
Copy the file specified by path-from to path-to. The return value is unspecified.

Scheme Procedure: rename-file oldname newname
C Function: scm_rename (oldname, newname)
Renames the file specified by oldname to newname. The return value is unspecified.

Scheme Procedure: link oldpath newpath
C Function: scm_link (oldpath, newpath)
Creates a new name newpath in the file system for the file named by oldpath. If oldpath is a symbolic link, the link may or may not be followed depending on the system.

Scheme Procedure: symlink oldpath newpath
C Function: scm_symlink (oldpath, newpath)
Create a symbolic link named path-to with the value (i.e., pointing to) path-from. The return value is unspecified.

Scheme Procedure: mkdir path [mode]
C Function: scm_mkdir (path, mode)
Create a new directory named by path. If mode is omitted then the permissions of the directory file are set using the current umask. Otherwise they are set to the decimal value specified with mode. The return value is unspecified.

Scheme Procedure: rmdir path
C Function: scm_rmdir (path)
Remove the existing directory named by path. The directory must be empty for this to succeed. The return value is unspecified.

Scheme Procedure: opendir dirname
C Function: scm_opendir (dirname)
Open the directory specified by path and return a directory stream.

Scheme Procedure: directory-stream? obj
C Function: scm_directory_stream_p (obj)
Return a boolean indicating whether object is a directory stream as returned by opendir.

Scheme Procedure: readdir port
C Function: scm_readdir (port)
Return (as a string) the next directory entry from the directory stream stream. If there is no remaining entry to be read then the end of file object is returned.

Scheme Procedure: rewinddir port
C Function: scm_rewinddir (port)
Reset the directory port stream so that the next call to readdir will return the first directory entry.

Scheme Procedure: closedir port
C Function: scm_closedir (port)
Close the directory stream stream. The return value is unspecified.

Scheme Procedure: sync
C Function: scm_sync ()
Flush the operating system disk buffers. The return value is unspecified.

Scheme Procedure: mknod path type perms dev
C Function: scm_mknod (path, type, perms, dev)
Creates a new special file, such as a file corresponding to a device. path specifies the name of the file. type should be one of the following symbols: regular, directory, symlink, block-special, char-special, fifo, or socket. perms (an integer) specifies the file permissions. dev (an integer) specifies which device the special file refers to. Its exact interpretation depends on the kind of special file being created.

E.g.,

(mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))

The return value is unspecified.

Scheme Procedure: tmpnam
C Function: scm_tmpnam ()
Return a name in the file system that does not match any existing file. However there is no guarantee that another process will not create the file after tmpnam is called. Care should be taken if opening the file, e.g., use the O_EXCL open flag or use mkstemp! instead.

Scheme Procedure: mkstemp! tmpl
C Function: scm_mkstemp (tmpl)
Create a new unique file in the file system and returns a new buffered port open for reading and writing to the file. tmpl is a string specifying where the file should be created: it must end with XXXXXX and will be changed in place to return the name of the temporary file.

Scheme Procedure: dirname filename
C Function: scm_dirname (filename)
Return the directory name component of the file name filename. If filename does not contain a directory component, . is returned.

Scheme Procedure: basename filename [suffix]
C Function: scm_basename (filename, suffix)
Return the base name of the file name filename. The base name is the file name without any directory components. If suffix is provided, and is equal to the end of basename, it is removed also.

User Information

The facilities in this section provide an interface to the user and group database. They should be used with care since they are not reentrant.

The following functions accept an object representing user information and return a selected component:

passwd:name
The name of the userid.
passwd:passwd
The encrypted passwd.
passwd:uid
The user id number.
passwd:gid
The group id number.
passwd:gecos
The full name.
passwd:dir
The home directory.
passwd:shell
The login shell.

Scheme Procedure: getpwuid uid
Look up an integer userid in the user database.

Scheme Procedure: getpwnam name
Look up a user name string in the user database.

Scheme Procedure: setpwent
Initializes a stream used by getpwent to read from the user database. The next use of getpwent will return the first entry. The return value is unspecified.

Scheme Procedure: getpwent
Return the next entry in the user database, using the stream set by setpwent.

Scheme Procedure: endpwent
Closes the stream used by getpwent. The return value is unspecified.

Scheme Procedure: setpw [arg]
C Function: scm_setpwent (arg)
If called with a true argument, initialize or reset the password data stream. Otherwise, close the stream. The setpwent and endpwent procedures are implemented on top of this.

Scheme Procedure: getpw [user]
C Function: scm_getpwuid (user)
Look up an entry in the user database. obj can be an integer, a string, or omitted, giving the behaviour of getpwuid, getpwnam or getpwent respectively.

The following functions accept an object representing group information and return a selected component:

group:name
The group name.
group:passwd
The encrypted group password.
group:gid
The group id number.
group:mem
A list of userids which have this group as a supplementary group.

Scheme Procedure: getgrgid gid
Look up an integer group id in the group database.

Scheme Procedure: getgrnam name
Look up a group name in the group database.

Scheme Procedure: setgrent
Initializes a stream used by getgrent to read from the group database. The next use of getgrent will return the first entry. The return value is unspecified.

Scheme Procedure: getgrent
Return the next entry in the group database, using the stream set by setgrent.

Scheme Procedure: endgrent
Closes the stream used by getgrent. The return value is unspecified.

Scheme Procedure: setgr [arg]
C Function: scm_setgrent (arg)
If called with a true argument, initialize or reset the group data stream. Otherwise, close the stream. The setgrent and endgrent procedures are implemented on top of this.

Scheme Procedure: getgr [name]
C Function: scm_getgrgid (name)
Look up an entry in the group database. obj can be an integer, a string, or omitted, giving the behaviour of getgrgid, getgrnam or getgrent respectively.

In addition to the accessor procedures for the user database, the following shortcut procedures are also available.

Scheme Procedure: cuserid
C Function: scm_cuserid ()
Return a string containing a user name associated with the effective user id of the process. Return #f if this information cannot be obtained.

Scheme Procedure: getlogin
C Function: scm_getlogin ()
Return a string containing the name of the user logged in on the controlling terminal of the process, or #f if this information cannot be obtained.

Time

Scheme Procedure: current-time
C Function: scm_current_time ()
Return the number of seconds since 1970-01-01 00:00:00 UTC, excluding leap seconds.

Scheme Procedure: gettimeofday
C Function: scm_gettimeofday ()
Return a pair containing the number of seconds and microseconds since 1970-01-01 00:00:00 UTC, excluding leap seconds. Note: whether true microsecond resolution is available depends on the operating system.

The following procedures either accept an object representing a broken down time and return a selected component, or accept an object representing a broken down time and a value and set the component to the value. The numbers in parentheses give the usual range.

tm:sec, set-tm:sec
Seconds (0-59).
tm:min, set-tm:min
Minutes (0-59).
tm:hour, set-tm:hour
Hours (0-23).
tm:mday, set-tm:mday
Day of the month (1-31).
tm:mon, set-tm:mon
Month (0-11).
tm:year, set-tm:year
Year (70-), the year minus 1900.
tm:wday, set-tm:wday
Day of the week (0-6) with Sunday represented as 0.
tm:yday, set-tm:yday
Day of the year (0-364, 365 in leap years).
tm:isdst, set-tm:isdst
Daylight saving indicator (0 for "no", greater than 0 for "yes", less than 0 for "unknown").
tm:gmtoff, set-tm:gmtoff
Time zone offset in seconds west of UTC (-46800 to 43200).
tm:zone, set-tm:zone
Time zone label (a string), not necessarily unique.

Scheme Procedure: localtime time [zone]
C Function: scm_localtime (time, zone)
Return an object representing the broken down components of time, an integer like the one returned by current-time. The time zone for the calculation is optionally specified by zone (a string), otherwise the TZ environment variable or the system default is used.

Scheme Procedure: gmtime time
C Function: scm_gmtime (time)
Return an object representing the broken down components of time, an integer like the one returned by current-time. The values are calculated for UTC.

Scheme Procedure: mktime sbd_time [zone]
C Function: scm_mktime (sbd_time, zone)
bd-time is an object representing broken down time and zone is an optional time zone specifier (otherwise the TZ environment variable or the system default is used).

Returns a pair: the car is a corresponding integer time value like that returned by current-time; the cdr is a broken down time object, similar to as bd-time but with normalized values.

Scheme Procedure: tzset
C Function: scm_tzset ()
Initialize the timezone from the TZ environment variable or the system default. It's not usually necessary to call this procedure since it's done automatically by other procedures that depend on the timezone.

Scheme Procedure: strftime format stime
C Function: scm_strftime (format, stime)
Formats a time specification time using template. time is an object with time components in the form returned by localtime or gmtime. template is a string which can include formatting specifications introduced by a % character. The formatting of month and day names is dependent on the current locale. The value returned is the formatted string. See section `Formatting Date and Time' in The GNU C Library Reference Manual.)

Scheme Procedure: strptime format string
C Function: scm_strptime (format, string)
Performs the reverse action to strftime, parsing string according to the specification supplied in template. The interpretation of month and day names is dependent on the current locale. The value returned is a pair. The car has an object with time components in the form returned by localtime or gmtime, but the time zone components are not usefully set. The cdr reports the number of characters from string which were used for the conversion.

Variable: internal-time-units-per-second
The value of this variable is the number of time units per second reported by the following procedures.

Scheme Procedure: times
C Function: scm_times ()
Return an object with information about real and processor time. The following procedures accept such an object as an argument and return a selected component:
tms:clock
The current real time, expressed as time units relative to an arbitrary base.
tms:utime
The CPU time units used by the calling process.
tms:stime
The CPU time units used by the system on behalf of the calling process.
tms:cutime
The CPU time units used by terminated child processes of the calling process, whose status has been collected (e.g., using waitpid).
tms:cstime
Similarly, the CPU times units used by the system on behalf of terminated child processes.

Scheme Procedure: get-internal-real-time
C Function: scm_get_internal_real_time ()
Return the number of time units since the interpreter was started.

Scheme Procedure: get-internal-run-time
C Function: scm_get_internal_run_time ()
Return the number of time units of processor time used by the interpreter. Both system and user time are included but subprocesses are not.

Runtime Environment

Scheme Procedure: program-arguments
Scheme Procedure: command-line
C Function: scm_program_arguments ()
Return the list of command line arguments passed to Guile, as a list of strings. The list includes the invoked program name, which is usually "guile", but excludes switches and parameters for command line options like -e and -l.

Scheme Procedure: getenv nam
C Function: scm_getenv (nam)
Looks up the string name in the current environment. The return value is #f unless a string of the form NAME=VALUE is found, in which case the string VALUE is returned.

Scheme Procedure: setenv name value
Modifies the environment of the current process, which is also the default environment inherited by child processes.

If value is #f, then name is removed from the environment. Otherwise, the string name=value is added to the environment, replacing any existing string with name matching name.

The return value is unspecified.

Scheme Procedure: environ [env]
C Function: scm_environ (env)
If env is omitted, return the current environment (in the Unix sense) as a list of strings. Otherwise set the current environment, which is also the default environment for child processes, to the supplied list of strings. Each member of env should be of the form NAME=VALUE and values of NAME should not be duplicated. If env is supplied then the return value is unspecified.

Scheme Procedure: putenv str
C Function: scm_putenv (str)
Modifies the environment of the current process, which is also the default environment inherited by child processes.

If string is of the form NAME=VALUE then it will be written directly into the environment, replacing any existing environment string with name matching NAME. If string does not contain an equal sign, then any existing string with name matching string will be removed.

The return value is unspecified.

Processes

Scheme Procedure: chdir str
C Function: scm_chdir (str)
Change the current working directory to path. The return value is unspecified.

Scheme Procedure: getcwd
C Function: scm_getcwd ()
Return the name of the current working directory.

Scheme Procedure: umask [mode]
C Function: scm_umask (mode)
If mode is omitted, returns a decimal number representing the current file creation mask. Otherwise the file creation mask is set to mode and the previous value is returned.

E.g., (umask #o022) sets the mask to octal 22, decimal 18.

Scheme Procedure: chroot path
C Function: scm_chroot (path)
Change the root directory to that specified in path. This directory will be used for path names beginning with `/'. The root directory is inherited by all children of the current process. Only the superuser may change the root directory.

Scheme Procedure: getpid
C Function: scm_getpid ()
Return an integer representing the current process ID.

Scheme Procedure: getgroups
C Function: scm_getgroups ()
Return a vector of integers representing the current supplementary group IDs.

Scheme Procedure: getppid
C Function: scm_getppid ()
Return an integer representing the process ID of the parent process.

Scheme Procedure: getuid
C Function: scm_getuid ()
Return an integer representing the current real user ID.

Scheme Procedure: getgid
C Function: scm_getgid ()
Return an integer representing the current real group ID.

Scheme Procedure: geteuid
C Function: scm_geteuid ()
Return an integer representing the current effective user ID. If the system does not support effective IDs, then the real ID is returned. (feature? 'EIDs) reports whether the system supports effective IDs.

Scheme Procedure: getegid
C Function: scm_getegid ()
Return an integer representing the current effective group ID. If the system does not support effective IDs, then the real ID is returned. (feature? 'EIDs) reports whether the system supports effective IDs.

Scheme Procedure: setuid id
C Function: scm_setuid (id)
Sets both the real and effective user IDs to the integer id, provided the process has appropriate privileges. The return value is unspecified.

Scheme Procedure: setgid id
C Function: scm_setgid (id)
Sets both the real and effective group IDs to the integer id, provided the process has appropriate privileges. The return value is unspecified.

Scheme Procedure: seteuid id
C Function: scm_seteuid (id)
Sets the effective user ID to the integer id, provided the process has appropriate privileges. If effective IDs are not supported, the real ID is set instead -- (feature? 'EIDs) reports whether the system supports effective IDs. The return value is unspecified.

Scheme Procedure: setegid id
C Function: scm_setegid (id)
Sets the effective group ID to the integer id, provided the process has appropriate privileges. If effective IDs are not supported, the real ID is set instead -- (feature? 'EIDs) reports whether the system supports effective IDs. The return value is unspecified.

Scheme Procedure: getpgrp
C Function: scm_getpgrp ()
Return an integer representing the current process group ID. This is the POSIX definition, not BSD.

Scheme Procedure: setpgid pid pgid
C Function: scm_setpgid (pid, pgid)
Move the process pid into the process group pgid. pid or pgid must be integers: they can be zero to indicate the ID of the current process. Fails on systems that do not support job control. The return value is unspecified.

Scheme Procedure: setsid
C Function: scm_setsid ()
Creates a new session. The current process becomes the session leader and is put in a new process group. The process will be detached from its controlling terminal if it has one. The return value is an integer representing the new process group ID.

Scheme Procedure: waitpid pid [options]
C Function: scm_waitpid (pid, options)
This procedure collects status information from a child process which has terminated or (optionally) stopped. Normally it will suspend the calling process until this can be done. If more than one child process is eligible then one will be chosen by the operating system.

The value of pid determines the behaviour:

pid greater than 0
Request status information from the specified child process.
pid equal to -1 or WAIT_ANY
Request status information for any child process.
pid equal to 0 or WAIT_MYPGRP
Request status information for any child process in the current process group.
pid less than -1
Request status information for any child process whose process group ID is -PID.

The options argument, if supplied, should be the bitwise OR of the values of zero or more of the following variables:

Variable: WNOHANG
Return immediately even if there are no child processes to be collected.

Variable: WUNTRACED
Report status information for stopped processes as well as terminated processes.

The return value is a pair containing:

  1. The process ID of the child process, or 0 if WNOHANG was specified and no process was collected.
  2. The integer status value.

The following three functions can be used to decode the process status code returned by waitpid.

Scheme Procedure: status:exit-val status
C Function: scm_status_exit_val (status)
Return the exit status value, as would be set if a process ended normally through a call to exit or _exit, if any, otherwise #f.

Scheme Procedure: status:term-sig status
C Function: scm_status_term_sig (status)
Return the signal number which terminated the process, if any, otherwise #f.

Scheme Procedure: status:stop-sig status
C Function: scm_status_stop_sig (status)
Return the signal number which stopped the process, if any, otherwise #f.

Scheme Procedure: system [cmd]
C Function: scm_system (cmd)
Execute cmd using the operating system's "command processor". Under Unix this is usually the default shell sh. The value returned is cmd's exit status as returned by waitpid, which can be interpreted using the functions above.

If system is called without arguments, return a boolean indicating whether the command processor is available.

Scheme Procedure: primitive-exit [status]
C Function: scm_primitive_exit (status)
Terminate the current process without unwinding the Scheme stack. This is would typically be useful after a fork. The exit status is status if supplied, otherwise zero.

Scheme Procedure: execl filename . args
C Function: scm_execl (filename, args)
Executes the file named by path as a new process image. The remaining arguments are supplied to the process; from a C program they are accessible as the argv argument to main. Conventionally the first arg is the same as path. All arguments must be strings.

If arg is missing, path is executed with a null argument list, which may have system-dependent side-effects.

This procedure is currently implemented using the execv system call, but we call it execl because of its Scheme calling interface.

Scheme Procedure: execlp filename . args
C Function: scm_execlp (filename, args)
Similar to execl, however if filename does not contain a slash then the file to execute will be located by searching the directories listed in the PATH environment variable.

This procedure is currently implemented using the execvp system call, but we call it execlp because of its Scheme calling interface.

Scheme Procedure: execle filename env . args
C Function: scm_execle (filename, env, args)
Similar to execl, but the environment of the new process is specified by env, which must be a list of strings as returned by the environ procedure.

This procedure is currently implemented using the execve system call, but we call it execle because of its Scheme calling interface.

Scheme Procedure: primitive-fork
C Function: scm_fork ()
Creates a new "child" process by duplicating the current "parent" process. In the child the return value is 0. In the parent the return value is the integer process ID of the child.

This procedure has been renamed from fork to avoid a naming conflict with the scsh fork.

Scheme Procedure: nice incr
C Function: scm_nice (incr)
Increment the priority of the current process by incr. A higher priority value means that the process runs less often. The return value is unspecified.

Scheme Procedure: setpriority which who prio
C Function: scm_setpriority (which, who, prio)
Set the scheduling priority of the process, process group or user, as indicated by which and who. which is one of the variables PRIO_PROCESS, PRIO_PGRP or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user identifier for PRIO_USER. A zero value of who denotes the current process, process group, or user. prio is a value in the range -20 and 20, the default priority is 0; lower priorities cause more favorable scheduling. Sets the priority of all of the specified processes. Only the super-user may lower priorities. The return value is not specified.

Scheme Procedure: getpriority which who
C Function: scm_getpriority (which, who)
Return the scheduling priority of the process, process group or user, as indicated by which and who. which is one of the variables PRIO_PROCESS, PRIO_PGRP or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user identifier for PRIO_USER. A zero value of who denotes the current process, process group, or user. Return the highest priority (lowest numerical value) of any of the specified processes.

Signals

Procedures to raise, handle and wait for signals.

Scheme Procedure: kill pid sig
C Function: scm_kill (pid, sig)
Sends a signal to the specified process or group of processes.

pid specifies the processes to which the signal is sent:

pid greater than 0
The process whose identifier is pid.
pid equal to 0
All processes in the current process group.
pid less than -1
The process group whose identifier is -pid
pid equal to -1
If the process is privileged, all processes except for some special system processes. Otherwise, all processes with the current effective user ID.

sig should be specified using a variable corresponding to the Unix symbolic name, e.g.,

Variable: SIGHUP
Hang-up signal.

Variable: SIGINT
Interrupt signal.

Scheme Procedure: raise sig
C Function: scm_raise (sig)
Sends a specified signal sig to the current process, where sig is as described for the kill procedure.

Scheme Procedure: sigaction signum [handler [flags]]
C Function: scm_sigaction (signum, handler, flags)
Install or report the signal handler for a specified signal.

signum is the signal number, which can be specified using the value of variables such as SIGINT.

If action is omitted, sigaction returns a pair: the CAR is the current signal hander, which will be either an integer with the value SIG_DFL (default action) or SIG_IGN (ignore), or the Scheme procedure which handles the signal, or #f if a non-Scheme procedure handles the signal. The CDR contains the current sigaction flags for the handler.

If action is provided, it is installed as the new handler for signum. action can be a Scheme procedure taking one argument, or the value of SIG_DFL (default action) or SIG_IGN (ignore), or #f to restore whatever signal handler was installed before sigaction was first used. Flags can optionally be specified for the new handler (SA_RESTART will always be added if it's available and the system is using restartable system calls.) The return value is a pair with information about the old handler as described above.

This interface does not provide access to the "signal blocking" facility. Maybe this is not needed, since the thread support may provide solutions to the problem of consistent access to data structures.

Scheme Procedure: restore-signals
C Function: scm_restore_signals ()
Return all signal handlers to the values they had before any call to sigaction was made. The return value is unspecified.

Scheme Procedure: alarm i
C Function: scm_alarm (i)
Set a timer to raise a SIGALRM signal after the specified number of seconds (an integer). It's advisable to install a signal handler for SIGALRM beforehand, since the default action is to terminate the process.

The return value indicates the time remaining for the previous alarm, if any. The new value replaces the previous alarm. If there was no previous alarm, the return value is zero.

Scheme Procedure: pause
C Function: scm_pause ()
Pause the current process (thread?) until a signal arrives whose action is to either terminate the current process or invoke a handler procedure. The return value is unspecified.

Scheme Procedure: sleep i
C Function: scm_sleep (i)
Wait for the given number of seconds (an integer) or until a signal arrives. The return value is zero if the time elapses or the number of seconds remaining otherwise.

Scheme Procedure: usleep i
C Function: scm_usleep (i)
Sleep for I microseconds. usleep is not available on all platforms.

Scheme Procedure: setitimer which_timer interval_seconds interval_microseconds value_seconds value_microseconds
C Function: scm_setitimer (which_timer, interval_seconds, interval_microseconds, value_seconds, value_microseconds)
Set the timer specified by which_timer according to the given interval_seconds, interval_microseconds, value_seconds, and value_microseconds values.

Return information about the timer's previous setting. Errors are handled as described in the guile info pages under "POSIX Interface Conventions".

The timers available are: ITIMER_REAL, ITIMER_VIRTUAL, and ITIMER_PROF.

The return value will be a list of two cons pairs representing the current state of the given timer. The first pair is the seconds and microseconds of the timer it_interval, and the second pair is the seconds and microseconds of the timer it_value.

Scheme Procedure: getitimer which_timer
C Function: scm_getitimer (which_timer)
Return information about the timer specified by which_timer Errors are handled as described in the guile info pages under "POSIX Interface Conventions".

The timers available are: ITIMER_REAL, ITIMER_VIRTUAL, and ITIMER_PROF.

The return value will be a list of two cons pairs representing the current state of the given timer. The first pair is the seconds and microseconds of the timer it_interval, and the second pair is the seconds and microseconds of the timer it_value.

Terminals and Ptys

Scheme Procedure: isatty? port
C Function: scm_isatty_p (port)
Return #t if port is using a serial non--file device, otherwise #f.

Scheme Procedure: ttyname port
C Function: scm_ttyname (port)
Return a string with the name of the serial terminal device underlying port.

Scheme Procedure: ctermid
C Function: scm_ctermid ()
Return a string containing the file name of the controlling terminal for the current process.

Scheme Procedure: tcgetpgrp port
C Function: scm_tcgetpgrp (port)
Return the process group ID of the foreground process group associated with the terminal open on the file descriptor underlying port.

If there is no foreground process group, the return value is a number greater than 1 that does not match the process group ID of any existing process group. This can happen if all of the processes in the job that was formerly the foreground job have terminated, and no other job has yet been moved into the foreground.

Scheme Procedure: tcsetpgrp port pgid
C Function: scm_tcsetpgrp (port, pgid)
Set the foreground process group ID for the terminal used by the file descriptor underlying port to the integer pgid. The calling process must be a member of the same session as pgid and must have the same controlling terminal. The return value is unspecified.

Pipes

The following procedures provide an interface to the popen and pclose system routines. The code is in a separate "popen" module:

(use-modules (ice-9 popen))

Scheme Procedure: open-pipe command modes
Executes the shell command command (a string) in a subprocess. A pipe to the process is created and returned. modes specifies whether an input or output pipe to the process is created: it should be the value of OPEN_READ or OPEN_WRITE.

Scheme Procedure: open-input-pipe command
Equivalent to open-pipe with mode OPEN_READ.

Scheme Procedure: open-output-pipe command
Equivalent to open-pipe with mode OPEN_WRITE.

Scheme Procedure: close-pipe port
Closes the pipe created by open-pipe, then waits for the process to terminate and returns its status value, See section Processes, for information on how to interpret this value.

close-port (see section Closing) can also be used to close a pipe, but doesn't return the status.

Networking

Network Address Conversion

This section describes procedures which convert internet addresses between numeric and string formats.

IPv4 Address Conversion

Scheme Procedure: inet-aton address
C Function: scm_inet_aton (address)
Convert an IPv4 Internet address from printable string (dotted decimal notation) to an integer. E.g.,
(inet-aton "127.0.0.1") => 2130706433

Scheme Procedure: inet-ntoa inetid
C Function: scm_inet_ntoa (inetid)
Convert an IPv4 Internet address to a printable (dotted decimal notation) string. E.g.,
(inet-ntoa 2130706433) => "127.0.0.1"

Scheme Procedure: inet-netof address
C Function: scm_inet_netof (address)
Return the network number part of the given IPv4 Internet address. E.g.,
(inet-netof 2130706433) => 127

Scheme Procedure: inet-lnaof address
C Function: scm_lnaof (address)
Return the local-address-with-network part of the given IPv4 Internet address, using the obsolete class A/B/C system. E.g.,
(inet-lnaof 2130706433) => 1

Scheme Procedure: inet-makeaddr net lna
C Function: scm_inet_makeaddr (net, lna)
Make an IPv4 Internet address by combining the network number net with the local-address-within-network number lna. E.g.,
(inet-makeaddr 127 1) => 2130706433

IPv6 Address Conversion

Scheme Procedure: inet-ntop family address
C Function: scm_inet_ntop (family, address)
Convert a network address into a printable string. Note that unlike the C version of this function, the input is an integer with normal host byte ordering. family can be AF_INET or AF_INET6. E.g.,
(inet-ntop AF_INET 2130706433) => "127.0.0.1"
(inet-ntop AF_INET6 (- (expt 2 128) 1)) =>
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

Scheme Procedure: inet-pton family address
C Function: scm_inet_pton (family, address)
Convert a string containing a printable network address to an integer address. Note that unlike the C version of this function, the result is an integer with normal host byte ordering. family can be AF_INET or AF_INET6. E.g.,
(inet-pton AF_INET "127.0.0.1") => 2130706433
(inet-pton AF_INET6 "::1") => 1

Network Databases

This section describes procedures which query various network databases. Care should be taken when using the database routines since they are not reentrant.

The Host Database

A host object is a structure that represents what is known about a network host, and is the usual way of representing a system's network identity inside software.

The following functions accept a host object and return a selected component:

Scheme Procedure: hostent:name host
The "official" hostname for host.
Scheme Procedure: hostent:aliases host
A list of aliases for host.
Scheme Procedure: hostent:addrtype host
The host address type. For hosts with Internet addresses, this will return AF_INET.
Scheme Procedure: hostent:length host
The length of each address for host, in bytes.
Scheme Procedure: hostent:addr-list host
The list of network addresses associated with host.

The following procedures are used to search the host database:

Scheme Procedure: gethost [host]
Scheme Procedure: gethostbyname hostname
Scheme Procedure: gethostbyaddr address
C Function: scm_gethost (host)
Look up a host by name or address, returning a host object. The gethost procedure will accept either a string name or an integer address; if given no arguments, it behaves like gethostent (see below). If a name or address is supplied but the address can not be found, an error will be thrown to one of the keys: host-not-found, try-again, no-recovery or no-data, corresponding to the equivalent h_error values. Unusual conditions may result in errors thrown to the system-error or misc_error keys.

The following procedures may be used to step through the host database from beginning to end.

Scheme Procedure: sethostent [stayopen]
Initialize an internal stream from which host objects may be read. This procedure must be called before any calls to gethostent, and may also be called afterward to reset the host entry stream. If stayopen is supplied and is not #f, the database is not closed by subsequent gethostbyname or gethostbyaddr calls, possibly giving an efficiency gain.

Scheme Procedure: gethostent
Return the next host object from the host database, or #f if there are no more hosts to be found (or an error has been encountered). This procedure may not be used before sethostent has been called.

Scheme Procedure: endhostent
Close the stream used by gethostent. The return value is unspecified.

Scheme Procedure: sethost [stayopen]
C Function: scm_sethost (stayopen)
If stayopen is omitted, this is equivalent to endhostent. Otherwise it is equivalent to sethostent stayopen.

The Network Database

The following functions accept an object representing a network and return a selected component:

Scheme Procedure: netent:name net
The "official" network name.
Scheme Procedure: netent:aliases net
A list of aliases for the network.
Scheme Procedure: netent:addrtype net
The type of the network number. Currently, this returns only AF_INET.
Scheme Procedure: netent:net net
The network number.

The following procedures are used to search the network database:

Scheme Procedure: getnet [net]
Scheme Procedure: getnetbyname net-name
Scheme Procedure: getnetbyaddr net-number
C Function: scm_getnet (net)
Look up a network by name or net number in the network database. The net-name argument must be a string, and the net-number argument must be an integer. getnet will accept either type of argument, behaving like getnetent (see below) if no arguments are given.

The following procedures may be used to step through the network database from beginning to end.

Scheme Procedure: setnetent [stayopen]
Initialize an internal stream from which network objects may be read. This procedure must be called before any calls to getnetent, and may also be called afterward to reset the net entry stream. If stayopen is supplied and is not #f, the database is not closed by subsequent getnetbyname or getnetbyaddr calls, possibly giving an efficiency gain.

Scheme Procedure: getnetent
Return the next entry from the network database.

Scheme Procedure: endnetent
Close the stream used by getnetent. The return value is unspecified.

Scheme Procedure: setnet [stayopen]
C Function: scm_setnet (stayopen)
If stayopen is omitted, this is equivalent to endnetent. Otherwise it is equivalent to setnetent stayopen.

The Protocol Database

The following functions accept an object representing a protocol and return a selected component:

Scheme Procedure: protoent:name protocol
The "official" protocol name.
Scheme Procedure: protoent:aliases protocol
A list of aliases for the protocol.
Scheme Procedure: protoent:proto protocol
The protocol number.

The following procedures are used to search the protocol database:

Scheme Procedure: getproto [protocol]
Scheme Procedure: getprotobyname name
Scheme Procedure: getprotobynumber number
C Function: scm_getproto (protocol)
Look up a network protocol by name or by number. getprotobyname takes a string argument, and getprotobynumber takes an integer argument. getproto will accept either type, behaving like getprotoent (see below) if no arguments are supplied.

The following procedures may be used to step through the protocol database from beginning to end.

Scheme Procedure: setprotoent [stayopen]
Initialize an internal stream from which protocol objects may be read. This procedure must be called before any calls to getprotoent, and may also be called afterward to reset the protocol entry stream. If stayopen is supplied and is not #f, the database is not closed by subsequent getprotobyname or getprotobynumber calls, possibly giving an efficiency gain.

Scheme Procedure: getprotoent
Return the next entry from the protocol database.

Scheme Procedure: endprotoent
Close the stream used by getprotoent. The return value is unspecified.

Scheme Procedure: setproto [stayopen]
C Function: scm_setproto (stayopen)
If stayopen is omitted, this is equivalent to endprotoent. Otherwise it is equivalent to setprotoent stayopen.

The Service Database

The following functions accept an object representing a service and return a selected component:

Scheme Procedure: servent:name serv
The "official" name of the network service.
Scheme Procedure: servent:aliases serv
A list of aliases for the network service.
Scheme Procedure: servent:port serv
The Internet port used by the service.
Scheme Procedure: servent:proto serv
The protocol used by the service. A service may be listed many times in the database under different protocol names.

The following procedures are used to search the service database:

Scheme Procedure: getserv [name [protocol]]
Scheme Procedure: getservbyname name protocol
Scheme Procedure: getservbyport port protocol
C Function: scm_getserv (name, protocol)
Look up a network service by name or by service number, and return a network service object. The protocol argument specifies the name of the desired protocol; if the protocol found in the network service database does not match this name, a system error is signalled.

The getserv procedure will take either a service name or number as its first argument; if given no arguments, it behaves like getservent (see below).

The following procedures may be used to step through the service database from beginning to end.

Scheme Procedure: setservent [stayopen]
Initialize an internal stream from which service objects may be read. This procedure must be called before any calls to getservent, and may also be called afterward to reset the service entry stream. If stayopen is supplied and is not #f, the database is not closed by subsequent getservbyname or getservbyport calls, possibly giving an efficiency gain.

Scheme Procedure: getservent
Return the next entry from the services database.

Scheme Procedure: endservent
Close the stream used by getservent. The return value is unspecified.

Scheme Procedure: setserv [stayopen]
C Function: scm_setserv (stayopen)
If stayopen is omitted, this is equivalent to endservent. Otherwise it is equivalent to setservent stayopen.

Network Sockets and Communication

Socket ports can be created using socket and socketpair. The ports are initially unbuffered, to make reading and writing to the same port more reliable. A buffer can be added to the port using setvbuf, See section Ports and File Descriptors.

The convention used for "host" vs "network" addresses is that addresses are always held in host order at the Scheme level. The procedures in this section automatically convert between host and network order when required. The arguments and return values are thus in host order.

Scheme Procedure: socket family style proto
C Function: scm_socket (family, style, proto)
Return a new socket port of the type specified by family, style and proto. All three parameters are integers. Supported values for family are AF_UNIX, AF_INET and AF_INET6. Typical values for style are SOCK_STREAM, SOCK_DGRAM and SOCK_RAW.

proto can be obtained from a protocol name using getprotobyname. A value of zero specifies the default protocol, which is usually right.

A single socket port cannot by used for communication until it has been connected to another socket.

Scheme Procedure: socketpair family style proto
C Function: scm_socketpair (family, style, proto)
Return a pair of connected (but unnamed) socket ports of the type specified by family, style and proto. Many systems support only socket pairs of the AF_UNIX family. Zero is likely to be the only meaningful value for proto.

Scheme Procedure: getsockopt sock level optname
C Function: scm_getsockopt (sock, level, optname)
Return the value of a particular socket option for the socket port sock. level is an integer code for type of option being requested, e.g., SOL_SOCKET for socket-level options. optname is an integer code for the option required and should be specified using one of the symbols SO_DEBUG, SO_REUSEADDR etc.

The returned value is typically an integer but SO_LINGER returns a pair of integers.

Scheme Procedure: setsockopt sock level optname value
C Function: scm_setsockopt (sock, level, optname, value)
Set the value of a particular socket option for the socket port sock. level is an integer code for type of option being set, e.g., SOL_SOCKET for socket-level options. optname is an integer code for the option to set and should be specified using one of the symbols SO_DEBUG, SO_REUSEADDR etc. value is the value to which the option should be set. For most options this must be an integer, but for SO_LINGER it must be a pair.

The return value is unspecified.

Scheme Procedure: shutdown sock how
C Function: scm_shutdown (sock, how)
Sockets can be closed simply by using close-port. The shutdown procedure allows reception or transmission on a connection to be shut down individually, according to the parameter how:
0
Stop receiving data for this socket. If further data arrives, reject it.
1
Stop trying to transmit data from this socket. Discard any data waiting to be sent. Stop looking for acknowledgement of data already sent; don't retransmit it if it is lost.
2
Stop both reception and transmission.

The return value is unspecified.

Scheme Procedure: connect sock fam address . args
C Function: scm_connect (sock, fam, address, args)
Initiate a connection from a socket using a specified address family to the address specified by address and possibly args. The format required for address and args depends on the family of the socket.

For a socket of family AF_UNIX, only address is specified and must be a string with the filename where the socket is to be created.

For a socket of family AF_INET, address must be an integer IPv4 host address and args must be a single integer port number.

For a socket of family AF_INET6, address must be an integer IPv6 host address and args may be up to three integers: port [flowinfo] [scope_id], where flowinfo and scope_id default to zero.

The return value is unspecified.

Scheme Procedure: bind sock fam address . args
C Function: scm_bind (sock, fam, address, args)
Assign an address to the socket port sock. Generally this only needs to be done for server sockets, so they know where to look for incoming connections. A socket without an address will be assigned one automatically when it starts communicating.

The format of address and args depends on the family of the socket.

For a socket of family AF_UNIX, only address is specified and must be a string with the filename where the socket is to be created.

For a socket of family AF_INET, address must be an integer IPv4 address and args must be a single integer port number.

The values of the following variables can also be used for address:

Variable: INADDR_ANY
Allow connections from any address.

Variable: INADDR_LOOPBACK
The address of the local host using the loopback device.

Variable: INADDR_BROADCAST
The broadcast address on the local network.

Variable: INADDR_NONE
No address.

For a socket of family AF_INET6, address must be an integer IPv6 address and args may be up to three integers: port [flowinfo] [scope_id], where flowinfo and scope_id default to zero.

The return value is unspecified.

Scheme Procedure: listen sock backlog
C Function: scm_listen (sock, backlog)
Enable sock to accept connection requests. backlog is an integer specifying the maximum length of the queue for pending connections. If the queue fills, new clients will fail to connect until the server calls accept to accept a connection from the queue.

The return value is unspecified.

Scheme Procedure: accept sock
C Function: scm_accept (sock)
Accept a connection on a bound, listening socket. If there are no pending connections in the queue, wait until one is available unless the non-blocking option has been set on the socket.

The return value is a pair in which the car is a new socket port for the connection and the cdr is an object with address information about the client which initiated the connection.

sock does not become part of the connection and will continue to accept new requests.

The following functions take a socket address object, as returned by accept and other procedures, and return a selected component.

sockaddr:fam
The socket family, typically equal to the value of AF_UNIX or AF_INET.
sockaddr:path
If the socket family is AF_UNIX, returns the path of the filename the socket is based on.
sockaddr:addr
If the socket family is AF_INET, returns the Internet host address.
sockaddr:port
If the socket family is AF_INET, returns the Internet port number.

Scheme Procedure: getsockname sock
C Function: scm_getsockname (sock)
Return the address of sock, in the same form as the object returned by accept. On many systems the address of a socket in the AF_FILE namespace cannot be read.

Scheme Procedure: getpeername sock
C Function: scm_getpeername (sock)
Return the address that sock is connected to, in the same form as the object returned by accept. On many systems the address of a socket in the AF_FILE namespace cannot be read.

Scheme Procedure: recv! sock buf [flags]
C Function: scm_recv (sock, buf, flags)
Receive data from a socket port. sock must already be bound to the address from which data is to be received. buf is a string into which the data will be written. The size of buf limits the amount of data which can be received: in the case of packet protocols, if a packet larger than this limit is encountered then some data will be irrevocably lost.

The optional flags argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

The value returned is the number of bytes read from the socket.

Note that the data is read directly from the socket file descriptor: any unread buffered port data is ignored.

Scheme Procedure: send sock message [flags]
C Function: scm_send (sock, message, flags)
Transmit the string message on a socket port sock. sock must already be bound to a destination address. The value returned is the number of bytes transmitted -- it's possible for this to be less than the length of message if the socket is set to be non-blocking. The optional flags argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

Note that the data is written directly to the socket file descriptor: any unflushed buffered port data is ignored.

Scheme Procedure: recvfrom! sock str [flags [start [end]]]
C Function: scm_recvfrom (sock, str, flags, start, end)
Return data from the socket port sock and also information about where the data was received from. sock must already be bound to the address from which data is to be received. str, is a string into which the data will be written. The size of str limits the amount of data which can be received: in the case of packet protocols, if a packet larger than this limit is encountered then some data will be irrevocably lost.

The optional flags argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

The value returned is a pair: the car is the number of bytes read from the socket and the cdr an address object in the same form as returned by accept. The address will given as #f if not available, as is usually the case for stream sockets.

The start and end arguments specify a substring of str to which the data should be written.

Note that the data is read directly from the socket file descriptor: any unread buffered port data is ignored.

Scheme Procedure: sendto sock message fam address . args_and_flags
C Function: scm_sendto (sock, message, fam, address, args_and_flags)
Transmit the string message on the socket port sock. The destination address is specified using the fam, address and args_and_flags arguments, in a similar way to the connect procedure. args_and_flags contains the usual connection arguments optionally followed by a flags argument, which is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

The value returned is the number of bytes transmitted -- it's possible for this to be less than the length of message if the socket is set to be non-blocking. Note that the data is written directly to the socket file descriptor: any unflushed buffered port data is ignored.

The following functions can be used to convert short and long integers between "host" and "network" order. Although the procedures above do this automatically for addresses, the conversion will still need to be done when sending or receiving encoded integer data from the network.

Scheme Procedure: htons value
C Function: scm_htons (value)
Convert a 16 bit quantity from host to network byte ordering. value is packed into 2 bytes, which are then converted and returned as a new integer.

Scheme Procedure: ntohs value
C Function: scm_ntohs (value)
Convert a 16 bit quantity from network to host byte ordering. value is packed into 2 bytes, which are then converted and returned as a new integer.

Scheme Procedure: htonl value
C Function: scm_htonl (value)
Convert a 32 bit quantity from host to network byte ordering. value is packed into 4 bytes, which are then converted and returned as a new integer.

Scheme Procedure: ntohl value
C Function: scm_ntohl (value)
Convert a 32 bit quantity from network to host byte ordering. value is packed into 4 bytes, which are then converted and returned as a new integer.

These procedures are inconvenient to use at present, but consider:

(define write-network-long
  (lambda (value port)
    (let ((v (make-uniform-vector 1 1 0)))
      (uniform-vector-set! v 0 (htonl value))
      (uniform-vector-write v port))))

(define read-network-long
  (lambda (port)
    (let ((v (make-uniform-vector 1 1 0)))
      (uniform-vector-read! v port)
      (ntohl (uniform-vector-ref v 0)))))

System Identification

This section lists the various procedures Guile provides for accessing information about the system it runs on.

Scheme Procedure: uname
C Function: scm_uname ()
Return an object with some information about the computer system the program is running on.

The following procedures accept an object as returned by uname and return a selected component.

utsname:sysname
The name of the operating system.
utsname:nodename
The network name of the computer.
utsname:release
The current release level of the operating system implementation.
utsname:version
The current version level within the release of the operating system.
utsname:machine
A description of the hardware.

Scheme Procedure: gethostname
C Function: scm_gethostname ()
Return the host name of the current processor.

Scheme Procedure: sethostname name
C Function: scm_sethostname (name)
Set the host name of the current processor to name. May only be used by the superuser. The return value is not specified.

Scheme Procedure: software-type
Return a symbol describing the current platform's operating system. This may be one of AIX, VMS, UNIX, COHERENT, WINDOWS, MS-DOS, OS/2, THINKC, AMIGA, ATARIST, MACH, or ACORN.

Note that most varieties of Unix are considered to be simply "UNIX". That is because when a program depends on features that are not present on every operating system, it is usually better to test for the presence or absence of that specific feature. The return value of software-type should only be used for this purpose when there is no other easy or unambiguous way of detecting such features.

Locales

Scheme Procedure: setlocale category [locale]
C Function: scm_setlocale (category, locale)
If locale is omitted, return the current value of the specified locale category as a system-dependent string. category should be specified using the values LC_COLLATE, LC_ALL etc.

Otherwise the specified locale category is set to the string locale and the new value is returned as a system-dependent string. If locale is an empty string, the locale will be set using environment variables.

Encryption

Please note that the procedures in this section are not suited for strong encryption, they are only interfaces to the well-known and common system library functions of the same name. They are just as good (or bad) as the underlying functions, so you should refer to your system documentation before using them.

Scheme Procedure: crypt key salt
C Function: scm_crypt (key, salt)
Encrypt key using salt as the salt value to the crypt(3) library call.

Although getpass is not an encryption procedure per se, it appears here because it is often used in combination with crypt:

Scheme Procedure: getpass prompt
C Function: scm_getpass (prompt)
Display prompt to the standard error output and read a password from `/dev/tty'. If this file is not accessible, it reads from standard input. The password may be up to 127 characters in length. Additional characters and the terminating newline character are discarded. While reading the password, echoing and the generation of signals by special characters is disabled.


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