'\"
'\" Copyright (c) 2005-2006 Donal K. Fellows
'\" Copyright (c) 2021 Nathan Coulter
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" Copyright (c) 2024 Nathan Coulter
'\"
'\" You may distribute and/or modify this program under the terms of the GNU
'\" Affero General Public License as published by the Free Software Foundation,
'\" either version 3 of the License, or (at your option) any later version.
'\"
'\" See the file "COPYING" for information on usage and redistribution.
.TH chan n 8.5 Tcl "Tcl Built-In Commands"
.so man.macros
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
chan \- Reads, writes and manipulates channels.
.SH SYNOPSIS
\fBchan \fIprocedure\fR ?\fIarg arg ...\fR?
.BE
.SH DESCRIPTION
.PP
\fBchan\fR provides procedures for reading from, writing to, and
otherwise manipulating channels like those created by \fBopen\fR and
\fBsocket\fR, or the default channels \fBstdin\fR, \fBstdout\fR or \fBstderr\fR
which correspond respectively to the standard input, output, and error streams
of the process.
Available procedures are:
.\" METHOD: blocked
.TP
\fBchan blocked \fIchannel\fR
.
Returns 1 when \fIchannel\fR is non-blocking and the last input operation on
\fIchannel\fR failed because it would have otherwise caused the process to
block, and 0 otherwise.
.\" METHOD: close
.TP
\fBchan close \fIchannel\fR ?\fIdirection\fR?
.
Closes \fIchannel\fR, deleting any existing event handlers established for it,
and returns the empty string. Once both sides of a \fIchannel\fR are closed,
\fIchannel\fR no-longer exists in the current \fBinterp\fR.
.RS
.PP
If \fIdirection\fR, which may be \fBread\fR or \fBwrite\fR or any unique
abbreviation of those words, is given, closes only that side of \fIchannel\fR.
If \fIchannel\fR is read-write and the write side is closed, it becomes
read-only, or if the read side is closed, it becomes write-only.
.PP
.PP
Discards any buffered input before closing the read side of \fIchannel\fR.
Fully flushes any output before closing the write side of \fIchannel\fR unless
it is non-blocking mode, where it makes \fIchannel\fR unavailable, returns
immediately, and flushes any buffered output the background before actually
closing \fIchannel\fR.
.PP
Returns an error if \fIchannel\fR is blocking and error occurs while flushing
output. Produces an error in the same manner as \fBexec\fR if a
process in a command pipeline created by \fBopen\fR returns an error (either by
returning a non-zero exit code or writing to its standard error file
descriptor).
.PP
If \fIchannel\fR is a command pipeline and is in blocking mode, waits
for the connected processes to complete before closing \fIchannel\fR.
.PP
Only affects the current interpreter. If \fIchannel\fR is open in any other
interpreter, its state is unchanged there. See \fBinterp\fR for a description
of channel sharing.
.PP
Closing one side of a socket or command pipeline may cause the underlying
system resource to be closed or destroyed, along with whatever side-effects
that entails for the process on the other side of the pipeline.
.PP
When the last interpreter sharing a channel is destroyed, the channel is
switched to blocking mode, fully flushed, and then closed.
.PP
Channels are automatically closed when an interpreter is destroyed and
also when the process exits.
From 8.6 on (TIP#398), nonblocking channels are no longer switched to
blocking mode when exiting; this guarantees a timely exit even when the
peer or a communication channel is stalled. To ensure proper flushing of
stalled nonblocking channels on exit, one must now either (a) actively
switch them back to blocking or (b) use the environment variable
\fBTCL_FLUSH_NONBLOCKING_ON_EXIT\fR, which when set and not equal to
.QW \fB0\fR
restores the previous behavior.
.RE
.\" METHOD: configure
.TP
\fBchan configure \fIchannel\fR ?\fIoption\fR? ?\fIvalue\fR? ?\fIoption value\fR?...
.
Sets or gets the configuration of \fIchannel\fR.
.RS
.PP
If no \fIoption\fR or \fIvalue\fR arguments are given, \fBchan configure\fR
returns a dictionary of option names and values for \fIchannel\fR. If
\fIoption\fR is supplied without a \fIvalue\fR, \fBchan configure\fR returns
the current value that option. If one or more values are given, \fBchan
configure\fR sets each of the given options to the corresponding \fIvalue\fR
and returns the empty string.
.PP
The following options are supported for all channels. Each type of
channel may provide additional options. Those options are described in the
relevant documentation. For example, additional options are documented for
\fBsocket\fR, and also for serial devices at \fBopen\fR.
.\" OPTION: -blocking
.TP
\fB\-blocking\fI boolean\fR
.
If \fB\-blocking\fR is set to \fBtrue\fR (default), reading from or writing to
\fIchannel\fR may cause the process to block indefinitely. Otherwise,
operations such as \fBchan gets\fR, \fBchan read\fR, \fBchan puts\fR, \fBchan
flush\fR, and \fBchan close\fR take care not to block. For non-blocking mode
to work correctly the event loop must be active, e.g. via
\fBTcl_DoOneEvent\fR or \fBvwait\fR or by using Tk, so that channel events
are processed.
.\" OPTION: -buffering
.TP
\fB\-buffering\fI newValue\fR
.
If \fInewValue\fR is \fBfull\fR, which is the default, output is buffered
until the internal buffer is full or until \fBchan flush\fR is called. If
\fInewValue\fR is \fBline\fR, output is flushed each time a end-of-line
character is written. If \fInewValue\fR is \fBnone\fR, output is flushed after
every output operation. For \fBstdin\fR, \fBstdout\fR, and channels that
connect to terminal-like devices, the default value is \fBline\fR. For
\fBstderr\fR the default value is \fBnone\fR.
.\" OPTION: -buffersize
.TP
\fB\-buffersize\fI newSize\fR
.
\fInewSize\fR, an integer no greater than one million, is the size in bytes of
any input or output buffers subsequently allocated for \fIchannel\fR.
.\" OPTION: -encoding
.TP
\fB\-encoding\fR \fIencoding\fR
.
Sets the encoding of \fIchannel\fR to \fIencoding\fR which should be one of the
encodings returned by \fBencoding names\fR.
Input is converted from the encoding into Unicode, and output is converted
from Unicode to the encoding.
.RS
.PP
The encoding of a new channel is the value of \fBencoding system\fR,
which returns the platform- and locale-dependent system encoding used to
interface with the operating system,
.RE
.\" OPTION: -eofchar
.TP
\fB\-eofchar\fI char\fR
.
\fIchar\fR signals the end of the data when it is encountered in the input.
If \fIchar\fR is the empty string, there is no special character that marks
the end of the data.
.RS
.PP
The default value is the empty string. The acceptable range is \ex01 -
\ex7f. A value outside this range results in an error.
.RE
.VS "TCL8.7 TIP656"
.\" OPTION: -profile
.TP
\fB\-profile\fI profile\fR
.
Indicates the encoding profile to be used on \fIchannel\fR. The encoding
transforms in use for the input and output of \fIchannel\fR will then be
subject to the rules of that profile. Any failures will result in a channel
error. See \fBPROFILES\fR in the \fBencoding(n)\fR documentation for details
about encoding profiles.
.VE "TCL8.7 TIP656"
.\" OPTION: -translation
.TP
\fB\-translation\fI translation\fR
.TP
\fB\-translation\fR \fB{\fIinTranslation outTranslation\fB}\fR
.
In Tcl a single line\-feed character (\fBlf\fR) represents the end of a
line. However, the end of a line of a may be represented differently on
different platforms, or even for different devices on the same platform. For
example, in UNIX \fBlf\fR is normally used in files, and a carriage-return
character followed by a line-feed character (\fBcrlf\fR) is
normally used in network connections. Therefore, when decoding, e.g. with
\fBchan gets\fR and \fBchan read\fR, each particular end-of-line representation
is translated into \fBlf\fR for Tcl. Before encoding, e.g. with \fBchan
puts\fR, each \fBlf\fR is translated to the approprate end\-of\-line
representation for the target. The default translation setting is \fBauto\fR,
which handles all the common cases. When needed, \fB\-translation\fR provides
explicit control over the end\-of\-line representation.
.RS
.PP
Returns the input translation if \fIchannel\fR is read\-only, the output
translation if \fIchannel\fR is write\-only, and both the input translation and
the output translation if \fIchannel\fR is read\-write. When two
translations are given, they indicate the input and output translation
respectively. When only one translation is given for a read\-write channel, it
is the translation for both input and output. The following values are
currently supported:
.IP \fBauto\fR
The default. For input each occurrence of \fBlf\fR, carriage-return character
(\fBcr\fR), or \fBcrlf\fR is translated into \fBlf\fR for Tcl. For output,
each \fBlf\fR is translated into a the appropriate representation for the
target: For all Unix variants it is \fBlf\fR, and for all Windows variants it
is \fBcrlf\fR, except that for sockets on all platforms it is \fBcrlf\fR for
both input and output.
.IP \fBbinary\fR
Like \fBlf\fR, prevents end-of-line translation, but also sets \fB\-eofchar\fR
to the empty string to disable it, and sets \fB\-encoding\fR to
\fBiso8859-1\fR. This one argument fully configures \fIchannel\fR for bytewise
input and output: Each byte is read from \fIchannel\fR as the Unicode
character having the same value as that byte, and each character written to
\fIchannel\fR is encoded a single byte having the value of the character. This
makes it possible to treat text as byte values as long as each character in
remains in the range of 0 to 255 so that the correspondance between a character
and a byte is maintained. For example, A JPEG image can be read from
\fIchannel\fR, manipulated, and then written back to \fIchannel\fR.
.IP \fBcr\fR
The end of a line is encoded as \fBcr\fR. For input, each \fBcr\fR is
translated to \fBlf\fR, and for output each \fBlf\fR is translated to \fBcr\fR.
.IP \fBcrlf\fR
The end of a line is encoded as a \fBcrlf\fR. For input, each \fBcrlf\fR is
translated to \fBlf\fR. For output, each \fBlf\fR is translated to \fBcrlf\fR.
This translation is typically used for network connections, and is also used on
Windows systems.
.IP \fBlf\fR
The end of a line is encoded as \fBlf\fR so no translations occur during either
input or output. This translation is typically used on UNIX platforms,
.RE
.RE
.\" METHOD: copy
.TP
\fBchan copy \fIinputChan outputChan\fR ?\fB\-size \fIsize\fR? ?\fB\-command \fIcallback\fR?
.
Reads characters from \fIinputChan\fR and writes them to \fIoutputChan\fR until
all characters are copied, blocking until the copy is complete and returning
the number of characters copied. Leverages internal buffers to avoid extra
copies and to avoid buffering too much data in main memory when copying large
files to slow destinations like network sockets.
.RS
.PP
\fB\-size\fR limits the number of characters copied.
.PP
If \fB\-command\fR is given, \fBchan copy\fR returns immediately, works in the
background, and calls \fIcallback\fR when the copy completes, providing as an
additional argument the number of characters written to \fIoutputChan\fR. If
an error occurs during the background copy, another argument provides message
for the error. \fIinputChan\fR and \fIoutputChan\fR are automatically
configured for non-blocking mode if needed. Background copying only works
correctly if events are being processed, e.g. via \fBvwait\fR or Tk.
.PP
During a background copy no other read operation may be performed on
\fIinputChan\fR, and no write operation may be performed on
\fIoutputChan\fR. However, write operations may by performed on
\fIinputChan\fR and read operations may be performed on \fIoutputChan\fR, as
exhibited by the bidirectional copy example below.
.PP
If either \fIinputChan\fR or \fIoutputChan\fR is closed while the copy is in
progress, copying ceases and \fBno\fR callback is made. If \fIinputChan\fR is
closed all data already queued is written to \fIoutputChan\fR.
.PP
There should be no event handler established for \fIinputChan\fR because it
may become readable during a background copy. An attempt to read or write from
within an event handler results result in the error, "channel busy". Any
wrong-sided I/O attempted (by a \fBchan event\fR handler or otherwise) results
in a
.QW "channel busy"
error.
.RE
.\" METHOD: create
.TP
\fBchan create \fImode cmdPrefix\fR
.
Creates a new channel, called a \fBreflected\fR channel, with \fIcmdPrefix\fR
as its handler, and returns the name of the channel. \fBcmdPrefix\fR is the
first words of a command that provides the interface for a \fBrefchan\fR.
.RS
.PP
\fBImode\fR is a list of one or more of the strings
.QW \fBread\fR
or
.QW \fBwrite\fR ,
indicating whether the channel is a read channel, a write channel, or both.
It is an error if the handler does not support the chosen mode.
.PP
The handler is called as needed from the global namespace at the top level, and
command resolution happens there at the time of the call. If the handler is
renamed or deleted any subsequent attempt to call it is an error, which may
not be able to describe the failure.
.PP
The handler is always called in the interpreter and thread it was created in,
even if the channel was shared with or moved into a different interpreter in a
different thread. This is achieved through event dispatch, so if the event
loop is not entered, e.g. by calling \fBTcl_DoOneEvent\fR or \fBvwait\fR or
using Tk, the thread performing the channel operation \fIblocks
indefinitely\fR, resulting in deadlock.
.PP
One side of a channel may be in one thread while the other side is in a
different thread, providing a stream-oriented bridge between the threads. This
provides a method for regular stream communication between threads as an
alternative to sending commands.
.PP
When the interpreter the handler is in is deleted each channel associated with
the handler is deleted as well, regardless of which interpreter or thread it
is currently in or shared with.
.PP
\fBchan create\fR is \fBsafe\fR and is accessible to safe interpreters. The
handler is always called in the safe interpreter it was created in.
.RE
.\" METHOD: eof
.TP
\fBchan eof \fIchannel\fR
.
Returns 1 if the last read on \fIchannel\fR failed because the end of the data
was already reached, and 0 otherwise.
.\" METHOD: event
.TP
\fBchan event \fIchannel event\fR ?\fIscript\fR?
.
Arranges for the given script, called a \fBchannel event handler\fR, to be
called whenever the given event, either
.QW \fBreadable\fR
or
.QW \fBwritable\fR
occurs on \fIchannel\fR, replacing any script that was previously set. If
\fIscript\fR is the empty string the current handler is deleted. If
\fIscript\fR is omitted, either the existing script or the empty string is
returned. For handlers to be processed, the event loop must be entered, e.g.
via \fBvwait\fR or \fBupdate\fR, or by using Tk.
.RS
.PP
\fIscript\fR is evaluated at the global level in the interpreter it was
established in. Any resulting error is handled in the background, i.e. via
\fBinterp bgerror\fR. In order to prevent an endless loop due to a buggy
handler, the handler is deleted if \fIscript\fR returns an error so that it is
not evaluated again.
.PP
Without an event handler, \fBchan gets\fR or \fBchan read\fR on \fIchannel\fR in
blocking mode may block until data becomes available, during which the
thread is unable to perform other work or respond to events on other channels.
This could cause the application to appear to
.QW "freeze up"
\&.
Channel event handlers allow events on \fIchannel\fR to direct channel handling
so that the reader or writer can continue to perform other processing while
waiting for a channel to become available and then handle channel operations
when the channel is ready for the operation.
.PP
\fIchannel\fR is considered to be readable if there is unread data
available on the underlying device. \fIchannel\fR is also considered to
be readable if there is unread data in an input buffer, except in the
special case where the most recent attempt to read from \fIchannel\fR
was a \fBchan gets\fR call that could not find a complete line in the
input buffer. This feature allows a file to be read a line at a time
in non-blocking mode using events. A channel is also considered to be
readable if an end of file or error condition is present on the
underlying file or device. It is important for \fIscript\fR to check
for these conditions and handle them appropriately; for example, if
there is no special check for end of file, an infinite loop may occur
where \fIscript\fR reads no data, returns, and is immediately invoked
again.
.PP
\fIchannel\fR is considered to be writable if at least one byte of data can be
written to the underlying file or device without blocking, or if an error
condition is present. Note that client sockets opened in asynchronous mode
become writable when they become connected or if the connection fails.
.PP
Event-driven channel handling works best for channels in non-blocking mode. In
blocking mode \fIchannel\fR blocks when \fBchan puts\fR writes more data than
\fIchannel\fR can accept at the moment, and also when \fBchan gets\fR or
\fBchan read\fR requests more data than is currently available. When
\fIchannel\fR blocks, the thread can not do any other processing or service any
other events. When \fIchannel\fR is in non-blocking mode a thread may to carry
on with other work and get back to \fIchannel\fR at the right time.
.RE
.\" METHOD: flush
.TP
\fBchan flush \fIchannel\fR
.
If \fIchannel\fR is in blocking mode, flushes all buffered output to the
destination and then returns. If \fIchannel\fR is non-blocking, returns
immediately while all buffered output is flushed in the background as soon as
possible.
.\" METHOD: gets
.TP
\fBchan gets \fIchannel\fR ?\fIvarName\fR?
.
Reads and returns the characters up to but not including the next end\-of\-line
representation or the end of the input, whichever comes first. If \fIvarName\fR
is given, stores the result in the variable named \fIvarName\fR and returns the
length of the line. If the line was terminated by the end of the input rather
than an end-of-line representation, a subsequent call to \fBchan eof\fR returns
1. If more input is needed and \fIchannel\fR is non-blocking, returns the
empty string or if \fIvarName\fR was given returns \-1.
.RS
.PP
If necessary use \fIvarName\fR along with a return value of 0 to determine that
a line is actually empty, as opposed to more input being needed to provide a
complete line. \fBchan eof\fR can then be used to determine whether more input
is forthcoming.
.PP
Returns an error with the POSIX error code \fBEILSEQ\fR if the encoding profile
for \fIchannel\fR is \fBstrict\fR and a decoding error occurs, in which case
the current position is unchanged and it may be possible to change the encoding
and continue to read the input. See \fBENCODING ERROR EXAMPLES\fR later.
.RE
.\" METHOD: isbinary
.TP
\fBchan isbinary \fIchannel\fR
.
Returns 1 if \fIchannel\fR is configured as described for \fB-translation
binary\fR, and 0 otherwise.
.\" METHOD: names
.TP
\fBchan names\fR ?\fIpattern\fR?
.
Returns a list of all channel names, or if \fIpattern\fR is given, only those
names that match according to the rules of \fBstring match\fR.
.\" METHOD: pending
.TP
\fBchan pending \fImode channel\fR
.
Returns the number of bytes of input
when \fImode\fR is
.QW\fBinput\fR
, or output when \fImode\fR is
.QW\fBoutput\fR
, that are currently internally buffered for \fIchannel\fR. Useful in a readable
event callback to impose limits on input line length to avoid a potential
denial-of-service attack where an extremely long line exceeds the available
memory to buffer it. Returns -1 if \fIchannel\fR was not opened for the mode in
question.
.\" METHOD: pipe
.TP
\fBchan pipe\fR
.
Creates a pipe, i.e. a readable channel and a writable channel, and returns the
names of these channels. Data written to the writable channel can be read from
the readable channel. Because the pipe is a real system-level pipe, it can be
connected to other processes using redirection. For example, to redirect
\fBstderr\fR from a subprocess into one channel, and \fBstdout\fR into another,
\fBexec\fR with "2>@" and ">@", each onto the writable side of a pipe, closing
the writable side immediately thereafter so that EOF is signaled on the read
side once the subprocess has closed its output, typically on exit.
.RS
.PP
Due to buffering, data written to one side of a pipe might not immediately
become available on the other side. Tcl's own buffers can be configured via
\fBchan configure -buffering\fR, but overall behaviour still depends on
operating system buffers outside of Tcl's control. Once the write side of the
channel is closed, any data remaining in the buffers is flushed through to the
read side. It may be useful to arrange for the connected process to flush at
some point after writing to the channel or to have it use some system-provided
mechanism to configure buffering. When two pipes are connected to the same
process, one to send data to the process, and one to read data from the
process, a deadlock may occur if the channels are in blocking mode: If
reading, the channel may block waiting for data that can never come because
buffers are only flushed on subsequent writes, and if writing, the channel may
block while waiting for the buffers to become free, which can never happen
because the reader can not read while the writer is blocking. To avoid this
issue, either put the channels into non-blocking mode and use event handlers,
or place the read channel and the write channel in separate interpreters in
separate threads.
.RE
.\" METHOD: pop
.TP
\fBchan pop \fIchannel\fR
.
Removes the topmost transformation handler from \fIchannel\fR if there is one,
and closes \fIchannel\fR otherwise. The result is normally the empty string,
but may be an error in some situations, e.g. when closing the underlying
resource results in an error.
.\" METHOD: postevent
.TP
\fBchan postevent \fIchannel eventSpec\fR
.
For use by handlers established with \fBchan create\fR. Notifies Tcl that
that one or more event(s) listed in \fIeventSpec\fR, each of which is either
.QW\fBread\fR
or
.QW\fBwrite\fR.
, have occurred.
.RS
.PP
For use only by handlers for \fIchannel\fR which must have been created by
\fBchan create\fR. It is an error to post an event for any other kind of
channel.
.PP
Since only the handlers for a reflected channel should post events it is
an error to post an event from any interpreter other than the interpreter that
created the channel.
.PP
It is an error to post an event that \fIchannel\fR has no interest in. See
\fBwatch\fR in the \fBrefchan\fR documentation for more information
.PP
\fBchan postevent\fR is available in safe interpreters, as any handler for a
reflected channel would have been created, and will be evaluated in that
interpreter as well.
.RE
.\" METHOD: push
.TP
\fBchan push \fIchannel cmdPrefix\fR
.
Adds a new transformation handler on top of \fIchannel\fR and returns a handle
for the transformation. \fIcmdPrefix\fR is the first words of a command that
provides the interface documented for \fBtranschan\fR, and transforms data on
\fIchannel\fR, It is an error if handler does not support the mode(s)
\fIchannel\fR is in.
.\" METHOD: puts
.TP
\fBchan puts\fR ?\fB\-nonewline\fR? ?\fIchannel\fR? \fIstring\fR
.
Writes \fIstring\fR and a line feed to \fIchannel\fR. If \fB\-nonewline\fR is
given, the trailing line feed is not written. The default channel is
\fBstdout\fR.
.RS
.PP
Each line feed in the output is translated to the appropriate end of line
sequence as per the \fB\-translation\fR configuration setting of \fIchannel\fR.
.PP
Because Tcl internally buffers output, characters written to \fIchannel\fR may not
immediately be available at the destination. Tcl normally delays output until
the buffer is full or \fIchannel\fR is closed. \fBchan flush\fR forces output in
the direction of the destination.
.PP
If \fIchannel\fR is in blocking mode and the write buffer fills up, blocks
until space in the buffer is available again. If \fIchannel\fR is in
non-blocking mode, returns immediately and the data is written in the
background as fast possible, constrained by the speed at which the
destination accepts it. Data written to a channel in non-blocking mode can only
actually be written to the underlying resource when the application enters the
event loop so that channel events can be processed. When a channel is in
non-blocking mode, Tcl's internal buffers can hold an arbitrary amount of data,
possibly consuming a large amount of memory. To avoid wasting memory, channels
in non-blocking mode should normally be handled using \fBchan event\fR, where
the application only invokes \fBchan puts\fR after being notified through a
file event handler that the channel is ready for more output data.
.PP
Returns an error with POSIX error code \fBEILSEQ\fR if the encoding profile of
\fIchannel\fR is \fBstrict\fR and the data cannot be encoded in the encoding
for the channel. The data that were successfully encoded up to the point of
error may be written to the channel.
.RE
.\" METHOD: read
.TP
\fBchan read \fIchannel\fR ?\fInumChars\fR?
.TP
\fBchan read \fR?\fB\-nonewline\fR? \fIchannel\fR
.
Reads and returns the next \fInumChars\fR characters from \fIchannel\fR. If
\fInumChars\fR is omitted, all available characters up to the end of the file
are read, or if \fIchannel\fR is in non-blocking mode, all currently-available
characters are read. If there is an error on \fIchannel\fR, reading ceases and
an error is returned. If \fInumChars\fR is not given, \fB\-nonewline\fR
may be given, causing any trailing line feed to be trimmed.
.RS
.PP
If \fIchannel\fR is in non-blocking mode, fewer characters than requested may be
returned. If \fIchannel\fR is configured to use a multi-byte encoding, bytes
that do not form a complete character are retained in the buffers until enough
bytes to complete the character accumulate, or the end of the data is reached.
\fB\-nonewline\fR is ignored if characters are returned before reaching the end
of the file.
.PP
Each end-of-line sequence according to the value of \fB\-translation\fR is
translated into a line feed.
.PP
When reading from a serial port, most applications should configure the channel
to be in non-blocking mode, but not necessarily use an event handler since most
serial ports are comparatively slow. It is entirely possible to get a
\fBreadable\fR event for each individual character. In blocking mode, \fBchan
read\fR blocks forever when reading to the end of the data if there is no
\fBchan configure -eofchar\fR configured for the channel.
.PP
If the encoding profile for \fIchannel\fR is \fBstrict\fR, raises an exception
with the POSIX error code \fBEILSEQ\fR if a decoding error is encountered when
reading. If \fIchannel\fR is blocking , advances the file pointer to the
beginning of the invalid input and returns the error. The input that was
successfully-decoded up to the first byte that resulted in an error is
available in as the \fB\-result read\fR entry in the error option dictionary.
If \fIchannel\fR is in non-blocking mode, returns the successfully-decoded
input. A subsequent read starts at the position of the invalid data
and raises a \fBEILSEQ\fR POSIX error exception. Unlike the blocking channel
case, the \fB\-result read\fR key is not present in the error option
dictionary. It may be possible to change the encoding for \fIchannel\fR in
order to read the input that previously resulted in the decoding error. See
\fBENCODING ERROR EXAMPLES\fR later.
.RE .\" METHOD: seek
.TP
\fBchan seek \fIchannel offset\fR ?\fIorigin\fR?
.
Sets the current position in \fIchannel\fR to integer \fIoffset\fR
bytes relative to \fIorigin\fR. A negative offset moves the current position
backwards from the origin. \fIorigin\fR is one of the
following:
.RS
.IP \fBstart\fR
The origin is the start of the data. This is the default.
.IP \fBcurrent\fR
The origin is the current position.
.IP \fBend\fR
The origin is the end of the data.
.PP
\fBChan seek\fR flushes all buffered output even if \fIchannel\fR is in
non-blocking mode, discards any buffered and unread input, and returns the
empty string or an error if \fIchannel\fR does not support seeking.
.PP
\fIoffset\fR values are byte offsets, not character offsets. Unlike \fBchan
read\fR, both \fBchan seek\fR and \fBchan tell\fR operate in terms of bytes,
not characters,
.RE
.\" METHOD: tell
.TP
\fBchan tell \fIchannel\fR
.
Returns the offset in bytes of the current position in the underlying data, or
-1 if \fIchannel\fR does not support seeking. The value can be passed to \fBchan
seek\fR to set current position to that offset.
.\" METHOD: truncate
.TP
\fBchan truncate \fIchannel\fR ?\fIlength\fR?
.
Flushes \fIchannel\fR and truncates the data in \fIchannel\fR to \fIlength\fR
bytes, or to the current position in bytes if \fIlength\fR is omitted.
.
.SH EXAMPLES
.SS "SIMPLE CHANNEL OPERATION EXAMPLES"
.PP
Instruct Tcl to always send output to \fBstdout\fR immediately,
whether or not it is to a terminal:
.PP
.CS
\fBfconfigure\fR stdout -buffering none
.CE
.PP
In the following example a file is opened using the encoding CP1252, which is
common on Windows, searches for a string, rewrites that part, and truncates the
file two lines later.
.PP
.CS
set f [open somefile.txt r+]
\fBchan configure\fR $f -encoding cp1252
set offset 0
\fI# Search for string "FOOBAR" in the file\fR
while {[\fBchan gets\fR $f line] >= 0} {
set idx [string first FOOBAR $line]
if {$idx >= 0} {
\fI# Found it; rewrite line\fR
\fBchan seek\fR $f [expr {$offset + $idx}]
\fBchan puts\fR -nonewline $f BARFOO
\fI# Skip to end of following line, and truncate\fR
\fBchan gets\fR $f
\fBchan gets\fR $f
\fBchan truncate\fR $f
\fI# Stop searching the file now\fR
break
}
\fI# Save offset of start of next line for later\fR
set offset [\fBchan tell\fR $f]
}
\fBchan close\fR $f
.CE
.PP
This example illustrates flushing of a channel. The user is
prompted for some information. Because the standard input channel
is line buffered, it must be flushed for the user to see the prompt.
.PP
.CS
chan puts -nonewline "Please type your name: "
\fBchan flush\fR stdout
chan gets stdin name
chan puts "Hello there, $name!"
.CE
.PP
This example reads a file one line at a time and prints it out with
the current line number attached to the start of each line.
.PP
.CS
set chan [open "some.file.txt"]
set lineNumber 0
while {[\fBchan gets\fR $chan line] >= 0} {
chan puts "[incr lineNumber]: $line"
}
chan close $chan
.CE
.PP
In this example illustrating event driven reads,
\fBGetData\fR will be called with the channel as an
argument whenever $chan becomes readable. The \fBread\fR call
reads whatever characters are currently available without blocking. Each
individual byte is interpreted as the corresponding Unicode character.
Here the channel has the fileevent removed when an end of file
occurs to avoid being continually called (see above). Alternatively
the channel may be closed on this condition.
.PP
.CS
proc GetData chan {
set data [chan read $chan]
chan puts "[string length $data] $data"
if {[chan eof $chan]} {
chan event $chan readable {}
}
}
chan configure $chan -blocking 0 -translation binary
\fBchan event\fR $chan readable [list GetData $chan]
.CE
.PP
The next example is similar but uses \fBchan gets\fR to read
line-oriented data.
.PP
.CS
proc GetData {chan} {
if {[chan gets $chan line] >= 0} {
chan puts $line
}
if {[chan eof $chan]} {
chan close $chan
}
}
chan configure $chan -blocking 0 -buffering line -translation crlf
\fBchan event\fR $chan readable [list GetData $chan]
.CE
.PP
A network server that echoes its input line-by-line without
preventing servicing of other connections at the same time:
.PP
.CS
# This is a very simple logger...
proc log message {
\fBchan puts\fR stdout $message
}
# This is called whenever a new client connects to the server
proc connect {chan host port} {
set clientName [format <%s:%d> $host $port]
log "connection from $clientName"
\fBchan configure\fR $chan -blocking 0 -buffering line
\fBchan event\fR $chan readable [list echoLine $chan $clientName]
}
# This is called whenever either at least one byte of input
# data is available, or the channel was closed by the client.
proc echoLine {chan clientName} {
\fBchan gets\fR $chan line
if {[\fBchan eof\fR $chan]} {
log "finishing connection from $clientName"
\fBchan close\fR $chan
} elseif {![\fBchan blocked\fR $chan]} {
# Didn't block waiting for end-of-line
log "$clientName - $line"
\fBchan puts\fR $chan $line
}
}
# Create the server socket and enter the event-loop to wait
# for incoming connections...
socket -server connect 12345
vwait forever
.CE
.PP
The following example reads a PPM-format image from a file
combining ASCII and binary content.
.PP
.CS
# Open the file and put it into Unix ASCII mode
set f [open teapot.ppm]
\fBchan configure\fR $f -encoding ascii -translation lf
# Get the header
if {[chan gets $f] ne "P6"} {
error "not a raw\-bits PPM"
}
# Read lines until we have got non-comment lines
# that supply us with three decimal values.
set words {}
while {[llength $words] < 3} {
chan gets $f line
if {[string match "#*" $line]} continue
lappend words {*}[join [scan $line %d%d%d]]
}
# Those words supply the size of the image and its
# overall depth per channel. Assign to variables.
lassign $words xSize ySize depth
# Now switch to binary mode to read each byte as a character, where each
# character corresponds to one pixel (red,green, or blue).
\fBchan configure\fR $f -translation binary
set numDataBytes [expr {3 * $xSize * $ySize}]
set data [chan read $f $numDataBytes]
close $f
.CE
.SS "FILE SEEK EXAMPLES"
.PP
Read a file twice:
.PP
.CS
set f [open file.txt]
set data1 [chan read $f]
\fBchan seek\fR $f 0
set data2 [chan read $f]
chan close $f
# $data1 eq $data2 if the file wasn't updated
.CE
.PP
Read the last 10 bytes from a file:
.PP
.CS
set f [open file.data]
# -translation binary guarantees no decoding errors since each possible value
# of a byte corresponds to a character. Most other encodings could report a
# decoding error.
chan configure $f -translation binary
\fBchan seek\fR $f -10 end
set data [chan read $f 10]
chan close $f
.CE
.PP
Read a line from a file channel only if it starts with \fBfoobar\fR:
.PP
.CS
# Save the offset in case we need to undo the read...
set offset [\fBtell\fR $chan]
if {[read $chan 6] eq "foobar"} {
gets $chan line
} else {
set line {}
# Undo the read...
seek $chan $offset
}
.CE
.SS "ENCODING ERROR EXAMPLES"
.PP
The example below illustrates handling of an encoding error encountered
during channel input. First, creation of a test file containing
the invalid UTF-8 sequence (\fBA \\xC3 B\fR):
.PP
.CS
% set f [open test_A_195_B.txt wb]; chan puts -nonewline $f A\\xC3B; chan close $f
.CE
.PP
An attempt to read the file results in an encoding error which is
then introspected by switching the channel to binary mode. In the
example, when the error is reported the file position remains
unchanged so that the \fBchan gets\fR would later return the
full line if called.
.PP
.CS
% set f [open test_A_195_B.txt r]
file384b6a8
% chan configure $f -encoding utf-8 -profile strict
% catch {chan gets $f} e d
1
% set d
-code 1 -level 0
-errorstack {INNER {invokeStk1 gets file384b6a8}}
-errorcode {POSIX EILSEQ {invalid or incomplete multibyte or wide character}}
-errorinfo {...} -errorline 1
% chan tell $f
0
% chan configure $f -translation binary -profile strict
% chan gets $f
AÃB
.CE
.PP
The following example is similar to the above but demonstrates recovery after a
blocking read. The successfully decoded data "A" is returned in the error options
dictionary key \fB\-result read\fR. The file position is advanced on the encoding error
position 1. The data at the error position is thus recovered by the next
\fBchan read\fR command.
.PP
.CS
% set f [open test_A_195_B.txt r]
file35a65a0
% chan configure $f -encoding utf-8 -profile strict -blocking 1
% catch {chan read $f} e d
1
% set d
-result {read A} -code 1 -level 0
-errorstack {INNER {invokeStk1 read file35a65a0}}
-errorcode {POSIX EILSEQ {invalid or incomplete multibyte or wide character}}
-errorinfo {...} -errorline 1
% chan tell $f
1
% chan configure $f -translation binary -profile strict
% chan read $f
ÃB
% chan close $f
.CE
.PP
Finally the same example, but this time with a non-blocking channel.
.PP
.CS
% set f [open test_A_195_B.txt r]
file35a65a0
% chan configure $f -encoding utf-8 -profile strict -blocking 0
% chan read $f
A
% chan tell $f
1
% catch {chan read $f} e d
1
% set d
-code 1 -level 0
-errorstack {INNER {invokeStk1 read file384b228}}
-errorcode {POSIX EILSEQ {invalid or incomplete multibyte or wide character}}
-errorinfo {...} -errorline 1
.CE
.SS "CHANNEL COPY EXAMPLES"
.PP
The first example transfers the contents of one channel exactly to
another. Note that when copying one file to another, it is better to
use \fBfile copy\fR which also copies file metadata (e.g. the file
access permissions) where possible.
.PP
.CS
\fBchan configure\fR $in -translation binary
\fBchan configure\fR $out -translation binary
\fBchan copy\fR $in $out
.CE
.PP
This second example shows how the callback gets
passed the number of bytes transferred.
It also uses vwait to put the application into the event loop.
Of course, this simplified example could be done without the command
callback.
.PP
.CS
proc Cleanup {in out bytes {error {}}} {
global total
set total $bytes
\fBchan close\fR $in
\fBchan close\fR $out
if {$error ne ""} {
# error occurred during the copy
}
}
set in [open $file1]
set out [socket $server $port]
\fBchan copy\fR $in $out -command [list Cleanup $in $out]
vwait total
.CE
.PP
The third example copies in chunks and tests for end of file
in the command callback.
.PP
.CS
proc CopyMore {in out chunk bytes {error {}}} {
global total done
incr total $bytes
if {($error ne "") || [\fBchan eof\fR $in]} {
set done $total
\fBchan close\fR $in
\fBchan close\fR $out
} else {
\fBchan copy\fR $in $out -size $chunk \e
-command [list CopyMore $in $out $chunk]
}
}
set in [open $file1]
set out [socket $server $port]
set chunk 1024
set total 0
\fBchan copy\fR $in $out -size $chunk \e
-command [list CopyMore $in $out $chunk]
vwait done
.CE
.PP
The fourth example starts an asynchronous, bidirectional copy between
two sockets. Those could also be pipes from two bidirectional pipelines
(e.g., \fI[open "|hal 9000" r+]\fR); the conversation will remain
essentially secret to the script, since all four \fBchan event\fR slots
are busy, though any transforms that are \fBchan push\fRed on the
channels will be able to observe the passing traffic.
.PP
.CS
proc Done {dir args} {
global flows done
\fBchan puts\fR "$dir is over."
incr flows -1
if {$flows <= 0} {
set done 1
}
}
set flows 2
\fBchan copy\fR $sok1 $sok2 -command [list Done UP]
\fBchan copy\fR $sok2 $sok1 -command [list Done DOWN]
vwait done
.CE
.SH "SEE ALSO"
close(n), eof(n), fblocked(n), fconfigure(n), fcopy(n), file(n),
fileevent(n), flush(n), gets(n), open(n), puts(n), read(n), seek(n),
socket(n), tell(n), refchan(n), transchan(n),
Tcl_StandardChannels(3)
.SH KEYWORDS
blocking, channel, end of file, events, input, non-blocking,
offset, output, readable, seek, stdio, tell, writable
'\" Local Variables:
'\" mode: nroff
'\" End: