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