Debian Codegraph @

doc/chan.n

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