Node:Ports and File Descriptors, Next:, Previous:Conventions, Up:POSIX



38.2 Ports and File Descriptors

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

File ports are implemented using low-level operating system I/O facilities, with optional buffering to improve efficiency see 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.

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

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

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

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

fdopen fdes modes Scheme Procedure
scm_fdopen (fdes, modes) C Function
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 open-file.

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

fdes->inport fdes Scheme Procedure
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.

fdes->outport fdes Scheme Procedure
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.

primitive-move->fdes port fd Scheme Procedure
scm_primitive_move_to_fdes (port, fd) C Function
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.

move->fdes port fdes Scheme Procedure
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.

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

fsync object Scheme Procedure
scm_fsync (object) C Function
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.

open path flags [mode] Scheme Procedure
scm_open (path, flags, mode) C Function
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:

O_RDONLY Variable
Open the file read-only.

O_WRONLY Variable
Open the file write-only.

O_RDWR Variable
Open the file read/write.

O_APPEND Variable
Append to the file instead of truncating.

O_CREAT Variable
Create the file if it does not already exist.

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

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

close fd_or_port Scheme Procedure
scm_close (fd_or_port) C Function
Similar to close-port (see close-port), 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.

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

unread-char char [port] Scheme Procedure
scm_unread_char (char, port) C Function
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.

unread-string str port Scheme Procedure
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.

pipe Scheme Procedure
scm_pipe () C Function
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.

dup->fdes fd_or_port [fd] Scheme Procedure
scm_dup_to_fdes (fd_or_port, fd) C Function
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.

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

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

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

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

duplicate-port port modes Scheme Procedure
Returns a new port which is opened on a duplicate of the file descriptor underlying port, with mode string modes as for open-file. 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).

redirect-port old new Scheme Procedure
scm_redirect_port (old, new) C Function
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.

dup2 oldfd newfd Scheme Procedure
scm_dup2 (oldfd, newfd) C Function
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.

port-mode port Scheme Procedure
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.

port-for-each proc Scheme Procedure
scm_port_for_each (proc) C Function
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.

setvbuf port mode [size] Scheme Procedure
scm_setvbuf (port, mode, size) C Function
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.

fcntl object cmd [value] Scheme Procedure
scm_fcntl (object, cmd, value) C Function
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.

flock file operation Scheme Procedure
scm_flock (file, operation) C Function
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.

select reads writes excepts [secs [usecs]] Scheme Procedure
scm_select (reads, writes, excepts, secs, usecs) C Function
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.