Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/tcl8.5.2/doc/chan.n @ 25

Last change on this file since 25 was 25, checked in by landauf, 16 years ago

added tcl to libs

File size: 33.8 KB
Line 
1'\"
2'\" Copyright (c) 2005-2006 Donal K. Fellows
3'\"
4'\" See the file "license.terms" for information on usage and redistribution
5'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
6'\"
7'\" RCS: @(#) $Id: chan.n,v 1.17 2007/12/13 15:22:32 dgp Exp $
8.so man.macros
9.TH chan n 8.5 Tcl "Tcl Built-In Commands"
10.BS
11'\" Note:  do not modify the .SH NAME line immediately below!
12.SH NAME
13chan \- Read, write and manipulate channels
14.SH SYNOPSIS
15\fBchan \fIoption\fR ?\fIarg arg ...\fR?
16.BE
17.SH DESCRIPTION
18.PP
19This command provides several operations for reading from, writing to
20and otherwise manipulating open channels (such as have been created
21with the \fBopen\fR and \fBsocket\fR commands, or the default named
22channels \fBstdin\fR, \fBstdout\fR or \fBstderr\fR which correspond to
23the process's standard input, output and error streams respectively).
24\fIOption\fR indicates what to do with the channel; any unique
25abbreviation for \fIoption\fR is acceptable. Valid options are:
26.TP
27\fBchan blocked \fIchannelId\fR
28.
29This tests whether the last input operation on the channel called
30\fIchannelId\fR failed because it would have otherwise caused the
31process to block, and returns 1 if that was the case. It returns 0
32otherwise. Note that this only ever returns 1 when the channel has
33been configured to be non-blocking; all Tcl channels have blocking
34turned on by default.
35.TP
36\fBchan close \fIchannelId\fR
37.
38Close and destroy the channel called \fIchannelId\fR. Note that this
39deletes all existing file-events registered on the channel.
40.RS
41.PP
42As part of closing the channel, all buffered output is flushed to the
43channel's output device, any buffered input is discarded, the
44underlying operating system resource is closed and \fIchannelId\fR
45becomes unavailable for future use.
46.PP
47If the channel is blocking, the command does not return until all
48output is flushed.  If the channel is nonblocking and there is
49unflushed output, the channel remains open and the command returns
50immediately; output will be flushed in the background and the channel
51will be closed when all the flushing is complete.
52.PP
53If \fIchannelId\fR is a blocking channel for a command pipeline then
54\fBchan close\fR waits for the child processes to complete.
55.PP
56If the channel is shared between interpreters, then \fBchan close\fR
57makes \fIchannelId\fR unavailable in the invoking interpreter but has
58no other effect until all of the sharing interpreters have closed the
59channel. When the last interpreter in which the channel is registered
60invokes \fBchan close\fR (or \fBclose\fR), the cleanup actions
61described above occur. See the \fBinterp\fR command for a description
62of channel sharing.
63.PP
64Channels are automatically closed when an interpreter is destroyed and
65when the process exits.  Channels are switched to blocking mode, to
66ensure that all output is correctly flushed before the process exits.
67.PP
68The command returns an empty string, and may generate an error if
69an error occurs while flushing output.  If a command in a command
70pipeline created with \fBopen\fR returns an error, \fBchan close\fR
71generates an error (similar to the \fBexec\fR command.)
72.RE
73.TP
74\fBchan configure \fIchannelId\fR ?\fIoptionName\fR? ?\fIvalue\fR? ?\fIoptionName value\fR?...
75.
76Query or set the configuration options of the channel named
77\fIchannelId\fR.
78.RS
79.PP
80If no \fIoptionName\fR or \fIvalue\fR arguments are supplied, the
81command returns a list containing alternating option names and values
82for the channel.  If \fIoptionName\fR is supplied but no \fIvalue\fR
83then the command returns the current value of the given option.  If
84one or more pairs of \fIoptionName\fR and \fIvalue\fR are supplied,
85the command sets each of the named options to the corresponding
86\fIvalue\fR; in this case the return value is an empty string.
87.PP
88The options described below are supported for all channels. In
89addition, each channel type may add options that only it supports. See
90the manual entry for the command that creates each type of channels
91for the options that that specific type of channel supports. For
92example, see the manual entry for the \fBsocket\fR command for its
93additional options.
94.TP
95\fB\-blocking\fR \fIboolean\fR
96.
97The \fB\-blocking\fR option determines whether I/O operations on the
98channel can cause the process to block indefinitely.  The value of the
99option must be a proper boolean value.  Channels are normally in
100blocking mode; if a channel is placed into nonblocking mode it will
101affect the operation of the \fBchan gets\fR, \fBchan read\fR, \fBchan
102puts\fR, \fBchan flush\fR, and \fBchan close\fR commands; see the
103documentation for those commands for details.  For nonblocking mode to
104work correctly, the application must be using the Tcl event loop
105(e.g. by calling \fBTcl_DoOneEvent\fR or invoking the \fBvwait\fR
106command).
107.TP
108\fB\-buffering\fR \fInewValue\fR
109.
110If \fInewValue\fR is \fBfull\fR then the I/O system will buffer output
111until its internal buffer is full or until the \fBchan flush\fR
112command is invoked. If \fInewValue\fR is \fBline\fR, then the I/O
113system will automatically flush output for the channel whenever a
114newline character is output. If \fInewValue\fR is \fBnone\fR, the I/O
115system will flush automatically after every output operation.  The
116default is for \fB\-buffering\fR to be set to \fBfull\fR except for
117channels that connect to terminal-like devices; for these channels the
118initial setting is \fBline\fR.  Additionally, \fBstdin\fR and
119\fBstdout\fR are initially set to \fBline\fR, and \fBstderr\fR is set
120to \fBnone\fR.
121.TP
122\fB\-buffersize\fR \fInewSize\fR
123.
124\fINewvalue\fR must be an integer; its value is used to set the size
125of buffers, in bytes, subsequently allocated for this channel to store
126input or output. \fINewvalue\fR must be a number of no more than one
127million, allowing buffers of up to one million bytes in size.
128.TP
129\fB\-encoding\fR \fIname\fR
130.
131This option is used to specify the encoding of the channel as one of
132the named encodings returned by \fBencoding names\fR or the special
133value \fBbinary\fR, so that the data can be converted to and from
134Unicode for use in Tcl.  For instance, in order for Tcl to read
135characters from a Japanese file in \fBshiftjis\fR and properly process
136and display the contents, the encoding would be set to \fBshiftjis\fR.
137Thereafter, when reading from the channel, the bytes in the Japanese
138file would be converted to Unicode as they are read.  Writing is also
139supported \- as Tcl strings are written to the channel they will
140automatically be converted to the specified encoding on output.
141.RS
142.PP
143If a file contains pure binary data (for instance, a JPEG image), the
144encoding for the channel should be configured to be \fBbinary\fR.  Tcl
145will then assign no interpretation to the data in the file and simply
146read or write raw bytes.  The Tcl \fBbinary\fR command can be used to
147manipulate this byte-oriented data.  It is usually better to set the
148\fB\-translation\fR option to \fBbinary\fR when you want to transfer
149binary data, as this turns off the other automatic interpretations of
150the bytes in the stream as well.
151.PP
152The default encoding for newly opened channels is the same platform-
153and locale-dependent system encoding used for interfacing with the
154operating system, as returned by \fBencoding system\fR.
155.RE
156.TP
157\fB\-eofchar\fR \fIchar\fR
158.TP
159\fB\-eofchar\fR \fB{\fIinChar outChar\fB}\fR
160.
161This option supports DOS file systems that use Control-z (\ex1a) as an
162end of file marker.  If \fIchar\fR is not an empty string, then this
163character signals end-of-file when it is encountered during input.
164For output, the end-of-file character is output when the channel is
165closed.  If \fIchar\fR is the empty string, then there is no special
166end of file character marker.  For read-write channels, a two-element
167list specifies the end of file marker for input and output,
168respectively.  As a convenience, when setting the end-of-file
169character for a read-write channel you can specify a single value that
170will apply to both reading and writing.  When querying the end-of-file
171character of a read-write channel, a two-element list will always be
172returned.  The default value for \fB\-eofchar\fR is the empty string
173in all cases except for files under Windows.  In that case the
174\fB\-eofchar\fR is Control-z (\ex1a) for reading and the empty string
175for writing.
176The acceptable range for \fB\-eofchar\fR values is \ex01 - \ex7f;
177attempting to set \fB\-eofchar\fR to a value outside of this range will
178generate an error.
179.TP
180\fB\-translation\fR \fImode\fR
181.TP
182\fB\-translation\fR \fB{\fIinMode outMode\fB}\fR
183.
184In Tcl scripts the end of a line is always represented using a single
185newline character (\en).  However, in actual files and devices the end
186of a line may be represented differently on different platforms, or
187even for different devices on the same platform.  For example, under
188UNIX newlines are used in files, whereas carriage-return-linefeed
189sequences are normally used in network connections.  On input (i.e.,
190with \fBchan gets\fR and \fBchan read\fR) the Tcl I/O system
191automatically translates the external end-of-line representation into
192newline characters.  Upon output (i.e., with \fBchan puts\fR), the I/O
193system translates newlines to the external end-of-line representation.
194The default translation mode, \fBauto\fR, handles all the common cases
195automatically, but the \fB\-translation\fR option provides explicit
196control over the end of line translations.
197.RS
198.PP
199The value associated with \fB\-translation\fR is a single item for
200read-only and write-only channels.  The value is a two-element list for
201read-write channels; the read translation mode is the first element of
202the list, and the write translation mode is the second element.  As a
203convenience, when setting the translation mode for a read-write channel
204you can specify a single value that will apply to both reading and
205writing.  When querying the translation mode of a read-write channel, a
206two-element list will always be returned.  The following values are
207currently supported:
208.TP
209\fBauto\fR
210.
211As the input translation mode, \fBauto\fR treats any of newline
212(\fBlf\fR), carriage return (\fBcr\fR), or carriage return followed by
213a newline (\fBcrlf\fR) as the end of line representation.  The end of
214line representation can even change from line-to-line, and all cases
215are translated to a newline.  As the output translation mode,
216\fBauto\fR chooses a platform specific representation; for sockets on
217all platforms Tcl chooses \fBcrlf\fR, for all Unix flavors, it chooses
218\fBlf\fR, and for the various flavors of Windows it chooses
219\fBcrlf\fR.  The default setting for \fB\-translation\fR is \fBauto\fR
220for both input and output.
221.TP
222\fBbinary\fR
223.
224No end-of-line translations are performed.  This is nearly identical
225to \fBlf\fR mode, except that in addition \fBbinary\fR mode also sets
226the end-of-file character to the empty string (which disables it) and
227sets the encoding to \fBbinary\fR (which disables encoding filtering).
228See the description of \fB\-eofchar\fR and \fB\-encoding\fR for more
229information.
230.TP
231\fBcr\fR
232.
233The end of a line in the underlying file or device is represented by a
234single carriage return character.  As the input translation mode,
235\fBcr\fR mode converts carriage returns to newline characters.  As the
236output translation mode, \fBcr\fR mode translates newline characters
237to carriage returns.
238.TP
239\fBcrlf\fR
240.
241The end of a line in the underlying file or device is represented by a
242carriage return character followed by a linefeed character.  As the
243input translation mode, \fBcrlf\fR mode converts
244carriage-return-linefeed sequences to newline characters.  As the
245output translation mode, \fBcrlf\fR mode translates newline characters
246to carriage-return-linefeed sequences.  This mode is typically used on
247Windows platforms and for network connections.
248.TP
249\fBlf\fR
250.
251The end of a line in the underlying file or device is represented by a
252single newline (linefeed) character.  In this mode no translations
253occur during either input or output.  This mode is typically used on
254UNIX platforms.
255.RE
256.RE
257.TP
258\fBchan copy \fIinputChan outputChan\fR ?\fB\-size \fIsize\fR? ?\fB\-command \fIcallback\fR?
259.
260Copy data from the channel \fIinputChan\fR, which must have been
261opened for reading, to the channel \fIoutputChan\fR, which must have
262been opened for writing. The \fBchan copy\fR command leverages the
263buffering in the Tcl I/O system to avoid extra copies and to avoid
264buffering too much data in main memory when copying large files to
265slow destinations like network sockets.
266.RS
267.PP
268The \fBchan copy\fR command transfers data from \fIinputChan\fR until
269end of file or \fIsize\fR bytes have been transferred. If no
270\fB\-size\fR argument is given, then the copy goes until end of file.
271All the data read from \fIinputChan\fR is copied to \fIoutputChan\fR.
272Without the \fB\-command\fR option, \fBchan copy\fR blocks until the
273copy is complete and returns the number of bytes written to
274\fIoutputChan\fR.
275.PP
276The \fB\-command\fR argument makes \fBchan copy\fR work in the
277background.  In this case it returns immediately and the
278\fIcallback\fR is invoked later when the copy completes.  The
279\fIcallback\fR is called with one or two additional arguments that
280indicates how many bytes were written to \fIoutputChan\fR.  If an
281error occurred during the background copy, the second argument is the
282error string associated with the error.  With a background copy, it is
283not necessary to put \fIinputChan\fR or \fIoutputChan\fR into
284non-blocking mode; the \fBchan copy\fR command takes care of that
285automatically.  However, it is necessary to enter the event loop by
286using the \fBvwait\fR command or by using Tk.
287.PP
288You are not allowed to do other I/O operations with \fIinputChan\fR or
289\fIoutputChan\fR during a background \fBchan copy\fR.  If either
290\fIinputChan\fR or \fIoutputChan\fR get closed while the copy is in
291progress, the current copy is stopped and the command callback is
292\fInot\fR made.  If \fIinputChan\fR is closed, then all data already
293queued for \fIoutputChan\fR is written out.
294.PP
295Note that \fIinputChan\fR can become readable during a background
296copy.  You should turn off any \fBchan event\fR or \fBfileevent\fR
297handlers during a background copy so those handlers do not interfere
298with the copy.  Any I/O attempted by a \fBchan event\fR or
299\fBfileevent\fR handler will get a
300.QW "channel busy"
301error.
302.PP
303\fBChan copy\fR translates end-of-line sequences in \fIinputChan\fR
304and \fIoutputChan\fR according to the \fB\-translation\fR option for
305these channels (see \fBchan configure\fR above).  The translations
306mean that the number of bytes read from \fIinputChan\fR can be
307different than the number of bytes written to \fIoutputChan\fR.  Only
308the number of bytes written to \fIoutputChan\fR is reported, either as
309the return value of a synchronous \fBchan copy\fR or as the argument
310to the callback for an asynchronous \fBchan copy\fR.
311.PP
312\fBChan copy\fR obeys the encodings and character translations
313configured for the channels. This means that the incoming characters
314are converted internally first UTF-8 and then into the encoding of the
315channel \fBchan copy\fR writes to (see \fBchan configure\fR above for
316details on the \fB\-encoding\fR and \fB\-translation\fR options). No
317conversion is done if both channels are set to encoding \fBbinary\fR
318and have matching translations. If only the output channel is set to
319encoding \fBbinary\fR the system will write the internal UTF-8
320representation of the incoming characters. If only the input channel
321is set to encoding \fBbinary\fR the system will assume that the
322incoming bytes are valid UTF-8 characters and convert them according
323to the output encoding. The behaviour of the system for bytes which
324are not valid UTF-8 characters is undefined in this case.
325.RE
326.TP
327\fBchan create \fImode cmdPrefix\fR
328.
329This subcommand creates a new script level channel using the command
330prefix \fIcmdPrefix\fR as its handler. Any such channel is called a
331\fBreflected\fR channel. The specified command prefix, \fBcmdPrefix\fR,
332must be a non-empty list, and should provide the API described in the
333\fBreflectedchan\fR manual page. The handle of the new channel is
334returned as the result of the \fBchan create\fR command, and the
335channel is open. Use either \fBclose\fR or \fBchan close\fR to remove
336the channel.
337.RS
338.PP
339The argument \fImode\fR specifies if the new channel is opened for
340reading, writing, or both. It has to be a list containing any of the
341strings
342.QW \fBread\fR
343or
344.QW \fBwrite\fR .
345The list must have at least one
346element, as a channel you can neither write to nor read from makes no
347sense. The handler command for the new channel must support the chosen
348mode, or an error is thrown.
349.PP
350The command prefix is executed in the global namespace, at the top of
351call stack, following the appending of arguments as described in the
352\fBreflectedchan\fR manual page. Command resolution happens at the
353time of the call. Renaming the command, or destroying it means that
354the next call of a handler method may fail, causing the channel
355command invoking the handler to fail as well. Depending on the
356subcommand being invoked, the error message may not be able to explain
357the reason for that failure.
358.PP
359Every channel created with this subcommand knows which interpreter it
360was created in, and only ever executes its handler command in that
361interpreter, even if the channel was shared with and/or was moved into
362a different interpreter. Each reflected channel also knows the thread
363it was created in, and executes its handler command only in that
364thread, even if the channel was moved into a different thread. To this
365end all invocations of the handler are forwarded to the original
366thread by posting special events to it. This means that the original
367thread (i.e. the thread that executed the \fBchan create\fR command)
368must have an active event loop, i.e. it must be able to process such
369events. Otherwise the thread sending them will \fIblock
370indefinitely\fR. Deadlock may occur.
371.PP
372Note that this permits the creation of a channel whose two endpoints
373live in two different threads, providing a stream-oriented bridge
374between these threads. In other words, we can provide a way for
375regular stream communication between threads instead of having to send
376commands.
377.PP
378When a thread or interpreter is deleted, all channels created with
379this subcommand and using this thread/interpreter as their computing
380base are deleted as well, in all interpreters they have been shared
381with or moved into, and in whatever thread they have been transfered
382to. While this pulls the rug out under the other thread(s) and/or
383interpreter(s), this cannot be avoided. Trying to use such a channel
384will cause the generation of a regular error about unknown channel
385handles.
386.PP
387This subcommand is \fBsafe\fR and made accessible to safe
388interpreters.  While it arranges for the execution of arbitrary Tcl
389code the system also makes sure that the code is always executed
390within the safe interpreter.
391.RE
392.TP
393\fBchan eof \fIchannelId\fR
394.
395Test whether the last input operation on the channel called
396\fIchannelId\fR failed because the end of the data stream was reached,
397returning 1 if end-of-file was reached, and 0 otherwise.
398.TP
399\fBchan event \fIchannelId event\fR ?\fIscript\fR?
400.
401Arrange for the Tcl script \fIscript\fR to be installed as a \fIfile
402event handler\fR to be called whenever the channel called
403\fIchannelId\fR enters the state described by \fIevent\fR (which must
404be either \fBreadable\fR or \fBwritable\fR); only one such handler may
405be installed per event per channel at a time.  If \fIscript\fR is the
406empty string, the current handler is deleted (this also happens if the
407channel is closed or the interpreter deleted).  If \fIscript\fR is
408omitted, the currently installed script is returned (or an empty
409string if no such handler is installed).  The callback is only
410performed if the event loop is being serviced (e.g. via \fBvwait\fR or
411\fBupdate\fR).
412.RS
413.PP
414A file event handler is a binding between a channel and a script, such
415that the script is evaluated whenever the channel becomes readable or
416writable.  File event handlers are most commonly used to allow data to
417be received from another process on an event-driven basis, so that the
418receiver can continue to interact with the user or with other channels
419while waiting for the data to arrive.  If an application invokes
420\fBchan gets\fR or \fBchan read\fR on a blocking channel when there is
421no input data available, the process will block; until the input data
422arrives, it will not be able to service other events, so it will
423appear to the user to
424.QW "freeze up" .
425With \fBchan event\fR, the
426process can tell when data is present and only invoke \fBchan gets\fR
427or \fBchan read\fR when they will not block.
428.PP
429A channel is considered to be readable if there is unread data
430available on the underlying device.  A channel is also considered to
431be readable if there is unread data in an input buffer, except in the
432special case where the most recent attempt to read from the channel
433was a \fBchan gets\fR call that could not find a complete line in the
434input buffer.  This feature allows a file to be read a line at a time
435in nonblocking mode using events.  A channel is also considered to be
436readable if an end of file or error condition is present on the
437underlying file or device.  It is important for \fIscript\fR to check
438for these conditions and handle them appropriately; for example, if
439there is no special check for end of file, an infinite loop may occur
440where \fIscript\fR reads no data, returns, and is immediately invoked
441again.
442.PP
443A channel is considered to be writable if at least one byte of data
444can be written to the underlying file or device without blocking, or
445if an error condition is present on the underlying file or device.
446Note that client sockets opened in asynchronous mode become writable
447when they become connected or if the connection fails.
448.PP
449Event-driven I/O works best for channels that have been placed into
450nonblocking mode with the \fBchan configure\fR command.  In blocking
451mode, a \fBchan puts\fR command may block if you give it more data
452than the underlying file or device can accept, and a \fBchan gets\fR
453or \fBchan read\fR command will block if you attempt to read more data
454than is ready; no events will be processed while the commands block.
455In nonblocking mode \fBchan puts\fR, \fBchan read\fR, and \fBchan
456gets\fR never block.
457.PP
458The script for a file event is executed at global level (outside the
459context of any Tcl procedure) in the interpreter in which the \fBchan
460event\fR command was invoked.  If an error occurs while executing the
461script then the command registered with \fBinterp bgerror\fR is used
462to report the error.  In addition, the file event handler is deleted
463if it ever returns an error; this is done in order to prevent infinite
464loops due to buggy handlers.
465.RE
466.TP
467\fBchan flush \fIchannelId\fR
468.
469Ensures that all pending output for the channel called \fIchannelId\fR
470is written.
471.RS
472.PP
473If the channel is in blocking mode the command does not return until
474all the buffered output has been flushed to the channel. If the
475channel is in nonblocking mode, the command may return before all
476buffered output has been flushed; the remainder will be flushed in the
477background as fast as the underlying file or device is able to absorb
478it.
479.RE
480.TP
481\fBchan gets \fIchannelId\fR ?\fIvarName\fR?
482.
483Reads the next line from the channel called \fIchannelId\fR. If
484\fIvarName\fR is not specified, the result of the command will be the
485line that has been read (without a trailing newline character) or an
486empty string upon end-of-file or, in non-blocking mode, if the data
487available is exhausted. If \fIvarName\fR is specified, the line that
488has been read will be written to the variable called \fIvarName\fR and
489result will be the number of characters that have been read or -1 if
490end-of-file was reached or, in non-blocking mode, if the data
491available is exhausted.
492.RS
493.PP
494If an end-of-file occurs while part way through reading a line, the
495partial line will be returned (or written into \fIvarName\fR). When
496\fIvarName\fR is not specified, the end-of-file case can be
497distinguished from an empty line using the \fBchan eof\fR command, and
498the partial-line-but-nonblocking case can be distinguished with the
499\fBchan blocked\fR command.
500.RE
501.TP
502\fBchan names\fR ?\fIpattern\fR?
503.
504Produces a list of all channel names. If \fIpattern\fR is specified,
505only those channel names that match it (according to the rules of
506\fBstring match\fR) will be returned.
507.TP
508\fBchan pending \fImode channelId\fR
509.
510Depending on whether \fImode\fR is \fBinput\fR or \fBoutput\fR,
511returns the number of
512bytes of input or output (respectively) currently buffered
513internally for \fIchannelId\fR (especially useful in a readable event
514callback to impose application-specific limits on input line lengths to avoid
515a potential denial-of-service attack where a hostile user crafts
516an extremely long line that exceeds the available memory to buffer it).
517Returns -1 if the channel was not opened for the mode in question.
518.TP
519\fBchan postevent \fIchannelId eventSpec\fR
520.
521This subcommand is used by command handlers specified with \fBchan
522create\fR. It notifies the channel represented by the handle
523\fIchannelId\fR that the event(s) listed in the \fIeventSpec\fR have
524occurred. The argument has to be a list containing any of the strings
525\fBread\fR and \fBwrite\fR. The list must contain at least one
526element as it does not make sense to invoke the command if there are
527no events to post.
528.RS
529.PP
530Note that this subcommand can only be used with channel handles that
531were created/opened by \fBchan create\fR. All other channels will
532cause this subcommand to report an error.
533.PP
534As only the Tcl level of a channel, i.e. its command handler, should
535post events to it we also restrict the usage of this command to the
536interpreter that created the channel. In other words, posting events
537to a reflected channel from an interpreter that does not contain it's
538implementation is not allowed. Attempting to post an event from any
539other interpreter will cause this subcommand to report an error.
540.PP
541Another restriction is that it is not possible to post events that the
542I/O core has not registered an interest in. Trying to do so will cause
543the method to throw an error. See the command handler method
544\fBwatch\fR described in \fBreflectedchan\fR, the document specifying
545the API of command handlers for reflected channels.
546.PP
547This command is \fBsafe\fR and made accessible to safe interpreters.
548It can trigger the execution of \fBchan event\fR handlers, whether in the
549current interpreter or in other interpreters or other threads, even
550where the event is posted from a safe interpreter and listened for by
551a trusted interpreter. \fBChan event\fR handlers are \fIalways\fR
552executed in the interpreter that set them up.
553.RE
554.TP
555\fBchan puts\fR ?\fB\-nonewline\fR? ?\fIchannelId\fR? \fIstring\fR
556.
557Writes \fIstring\fR to the channel named \fIchannelId\fR followed by a
558newline character. A trailing newline character is written unless the
559optional flag \fB\-nonewline\fR is given. If \fIchannelId\fR is
560omitted, the string is written to the standard output channel,
561\fBstdout\fR.
562.RS
563.PP
564Newline characters in the output are translated by \fBchan puts\fR to
565platform-specific end-of-line sequences according to the currently
566configured value of the \fB\-translation\fR option for the channel
567(for example, on PCs newlines are normally replaced with
568carriage-return-linefeed sequences; see \fBchan configure\fR above for
569details).
570.PP
571Tcl buffers output internally, so characters written with \fBchan
572puts\fR may not appear immediately on the output file or device; Tcl
573will normally delay output until the buffer is full or the channel is
574closed.  You can force output to appear immediately with the \fBchan
575flush\fR command.
576.PP
577When the output buffer fills up, the \fBchan puts\fR command will
578normally block until all the buffered data has been accepted for
579output by the operating system.  If \fIchannelId\fR is in nonblocking
580mode then the \fBchan puts\fR command will not block even if the
581operating system cannot accept the data.  Instead, Tcl continues to
582buffer the data and writes it in the background as fast as the
583underlying file or device can accept it.  The application must use the
584Tcl event loop for nonblocking output to work; otherwise Tcl never
585finds out that the file or device is ready for more output data.  It
586is possible for an arbitrarily large amount of data to be buffered for
587a channel in nonblocking mode, which could consume a large amount of
588memory.  To avoid wasting memory, nonblocking I/O should normally be
589used in an event-driven fashion with the \fBchan event\fR command
590(do not invoke \fBchan puts\fR unless you have recently been notified
591via a file event that the channel is ready for more output data).
592.RE
593.TP
594\fBchan read \fIchannelId\fR ?\fInumChars\fR?
595.TP
596\fBchan read \fR?\fB\-nonewline\fR? \fIchannelId\fR
597.
598In the first form, the result will be the next \fInumChars\fR
599characters read from the channel named \fIchannelId\fR; if
600\fInumChars\fR is omitted, all characters up to the point when the
601channel would signal a failure (whether an end-of-file, blocked or
602other error condition) are read. In the second form (i.e. when
603\fInumChars\fR has been omitted) the flag \fB\-nonewline\fR may be
604given to indicate that any trailing newline in the string that has
605been read should be trimmed.
606.RS
607.PP
608If \fIchannelId\fR is in nonblocking mode, \fBchan read\fR may not
609read as many characters as requested: once all available input has
610been read, the command will return the data that is available rather
611than blocking for more input.  If the channel is configured to use a
612multi-byte encoding, then there may actually be some bytes remaining
613in the internal buffers that do not form a complete character.  These
614bytes will not be returned until a complete character is available or
615end-of-file is reached.  The \fB\-nonewline\fR switch is ignored if
616the command returns before reaching the end of the file.
617.PP
618\fBChan read\fR translates end-of-line sequences in the input into
619newline characters according to the \fB\-translation\fR option for the
620channel (see \fBchan configure\fR above for a discussion on the ways
621in which \fBchan configure\fR will alter input).
622.PP
623When reading from a serial port, most applications should configure
624the serial port channel to be nonblocking, like this:
625.CS
626\fBchan configure \fIchannelId \fB\-blocking \fI0\fR.
627.CE
628Then \fBchan read\fR behaves much like described above.  Note that
629most serial ports are comparatively slow; it is entirely possible to
630get a \fBreadable\fR event for each character read from them. Care
631must be taken when using \fBchan read\fR on blocking serial ports:
632.TP
633\fBchan read \fIchannelId numChars\fR
634.
635In this form \fBchan read\fR blocks until \fInumChars\fR have been
636received from the serial port.
637.TP
638\fBchan read \fIchannelId\fR
639.
640In this form \fBchan read\fR blocks until the reception of the
641end-of-file character, see \fBchan configure -eofchar\fR. If there no
642end-of-file character has been configured for the channel, then
643\fBchan read\fR will block forever.
644.RE
645.TP
646\fBchan seek \fIchannelId offset\fR ?\fIorigin\fR?
647.
648Sets the current access position within the underlying data stream for
649the channel named \fIchannelId\fR to be \fIoffset\fR bytes relative to
650\fIorigin\fR. \fIOffset\fR must be an integer (which may be negative)
651and \fIorigin\fR must be one of the following:
652.RS
653.TP 10
654\fBstart\fR
655.
656The new access position will be \fIoffset\fR bytes from the start
657of the underlying file or device.
658.TP 10
659\fBcurrent\fR
660.
661The new access position will be \fIoffset\fR bytes from the current
662access position; a negative \fIoffset\fR moves the access position
663backwards in the underlying file or device.
664.TP 10
665\fBend\fR
666.
667The new access position will be \fIoffset\fR bytes from the end of the
668file or device.  A negative \fIoffset\fR places the access position
669before the end of file, and a positive \fIoffset\fR places the access
670position after the end of file.
671.PP
672The \fIorigin\fR argument defaults to \fBstart\fR.
673.PP
674\fBChan seek\fR flushes all buffered output for the channel before the
675command returns, even if the channel is in nonblocking mode.  It also
676discards any buffered and unread input.  This command returns an empty
677string.  An error occurs if this command is applied to channels whose
678underlying file or device does not support seeking.
679.PP
680Note that \fIoffset\fR values are byte offsets, not character offsets.
681Both \fBchan seek\fR and \fBchan tell\fR operate in terms of bytes,
682not characters, unlike \fBchan read\fR.
683.RE
684.TP
685\fBchan tell \fIchannelId\fR
686.
687Returns a number giving the current access position within the
688underlying data stream for the channel named \fIchannelId\fR. This
689value returned is a byte offset that can be passed to \fBchan seek\fR
690in order to set the channel to a particular position.  Note that this
691value is in terms of bytes, not characters like \fBchan read\fR.  The
692value returned is -1 for channels that do not support seeking.
693.TP
694\fBchan truncate \fIchannelId\fR ?\fIlength\fR?
695.
696Sets the byte length of the underlying data stream for the channel
697named \fIchannelId\fR to be \fIlength\fR (or to the current byte
698offset within the underlying data stream if \fIlength\fR is
699omitted). The channel is flushed before truncation.
700.SH EXAMPLE
701This opens a file using a known encoding (CP1252, a very common encoding
702on Windows), searches for a string, rewrites that part, and truncates the
703file after a further two lines.
704.PP
705.CS
706set f [open somefile.txt r+]
707\fBchan configure\fR $f -encoding cp1252
708set offset 0
709
710\fI# Search for string "FOOBAR" in the file\fR
711while {[\fBchan gets\fR $f line] >= 0} {
712   set idx [string first FOOBAR $line]
713   if {$idx > -1} {
714      \fI# Found it; rewrite line\fR
715
716      \fBchan seek\fR $f [expr {$offset + $idx}]
717      \fBchan puts\fR -nonewline $f BARFOO
718
719      \fI# Skip to end of following line, and truncate\fR
720      \fBchan gets\fR $f
721      \fBchan gets\fR $f
722      \fBchan truncate\fR $f
723
724      \fI# Stop searching the file now\fR
725      break
726   }
727
728   \fI# Save offset of start of next line for later\fR
729   set offset [\fBchan tell\fR $f]
730}
731\fBchan close\fR $f
732.CE
733.SH "SEE ALSO"
734close(n), eof(n), fblocked(n), fconfigure(n), fcopy(n), file(n),
735fileevent(n), flush(n), gets(n), open(n), puts(n), read(n), seek(n),
736socket(n), tell(n), refchan(n)
737.SH KEYWORDS
738channel, input, output, events, offset
Note: See TracBrowser for help on using the repository browser.