1chan(n)                      Tcl Built-In Commands                     chan(n)
2
3
4
5______________________________________________________________________________
6

NAME

8       chan - Read, write and manipulate channels
9

SYNOPSIS

11       chan option ?arg arg ...?
12______________________________________________________________________________
13

DESCRIPTION

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 re‐
27              turns 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 ac‐
68              tions 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 in‐
147                     stance, in order for Tcl to read characters from a  Japa‐
148                     nese  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  ac‐
200                     tual  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, un‐
203                     der UNIX newlines are used in files, whereas carriage-re‐
204                     turn-linefeed sequences are normally used in network con‐
205                     nections.  On input (i.e., with chan gets and chan  read)
206                     the  Tcl I/O system automatically translates the external
207                     end-of-line representation into newline characters.  Upon
208                     output  (i.e., with chan puts), the I/O system translates
209                     newlines to the external end-of-line representation.  The
210                     default  translation  mode,  auto, handles all the common
211                     cases automatically, but the -translation option provides
212                     explicit control over the end of line translations.
213
214                     The  value  associated with -translation is a single item
215                     for read-only and write-only channels.  The  value  is  a
216                     two-element list for read-write channels; the read trans‐
217                     lation mode is the first element of  the  list,  and  the
218                     write  translation mode is the second element.  As a con‐
219                     venience, when setting the translation mode for  a  read-
220                     write  channel  you  can specify a single value that will
221                     apply to both reading and  writing.   When  querying  the
222                     translation  mode  of a read-write channel, a two-element
223                     list will always be returned.  The following  values  are
224                     currently supported:
225
226                     auto   As  the input translation mode, auto treats any of
227                            newline (lf), carriage return  (cr),  or  carriage
228                            return  followed by a newline (crlf) as the end of
229                            line representation.  The end of line  representa‐
230                            tion  can  even  change from line-to-line, and all
231                            cases are translated to a newline.  As the  output
232                            translation mode, auto chooses a platform specific
233                            representation; for sockets on all  platforms  Tcl
234                            chooses crlf, for all Unix flavors, it chooses lf,
235                            and for the various flavors of Windows it  chooses
236                            crlf.   The  default  setting  for -translation is
237                            auto for both input and output.
238
239                     binary No end-of-line translations are  performed.   This
240                            is nearly identical to lf mode, except that in ad‐
241                            dition binary mode also sets the end-of-file char‐
242                            acter  to the empty string (which disables it) and
243                            sets the encoding to binary (which disables encod‐
244                            ing  filtering).   See the description of -eofchar
245                            and -encoding for more information.
246
247                     cr     The end of a line in the underlying file or device
248                            is represented by a single carriage return charac‐
249                            ter.  As the input translation mode, cr mode  con‐
250                            verts  carriage returns to newline characters.  As
251                            the output translation mode,  cr  mode  translates
252                            newline characters to carriage returns.
253
254                     crlf   The end of a line in the underlying file or device
255                            is represented by a carriage return character fol‐
256                            lowed  by  a  linefeed  character.   As  the input
257                            translation mode, crlf mode converts  carriage-re‐
258                            turn-linefeed sequences to newline characters.  As
259                            the output translation mode, crlf mode  translates
260                            newline characters to carriage-return-linefeed se‐
261                            quences.  This mode is typically used  on  Windows
262                            platforms and for network connections.
263
264                     lf     The end of a line in the underlying file or device
265                            is represented  by  a  single  newline  (linefeed)
266                            character.   In  this  mode  no translations occur
267                            during either input or output.  This mode is typi‐
268                            cally used on UNIX platforms.
269
270       chan copy inputChan outputChan ?-size size? ?-command callback?
271              Copy  data  from  the  channel  inputChan,  which must have been
272              opened for reading, to the channel outputChan, which  must  have
273              been  opened  for  writing.  The chan copy command leverages the
274              buffering in the Tcl I/O system to avoid  extra  copies  and  to
275              avoid  buffering too much data in main memory when copying large
276              files to slow destinations like network sockets.
277
278              The chan copy command transfers data from inputChan until end of
279              file  or size bytes or characters have been transferred; size is
280              in bytes if the two channels are using the same encoding, and is
281              in  characters  otherwise.   If no -size argument is given, then
282              the copy goes until end of file. All  the  data  read  from  in‐
283              putChan  is  copied to outputChan.  Without the -command option,
284              chan copy blocks until the copy is complete and returns the num‐
285              ber  of  bytes  or  characters  (using the same rules as for the
286              -size option) written to outputChan.
287
288              The -command argument makes chan copy work  in  the  background.
289              In  this case it returns immediately and the callback is invoked
290              later when the copy completes.  The callback is called with  one
291              or  two  additional arguments that indicates how many bytes were
292              written to outputChan.  If an error occurred  during  the  back‐
293              ground  copy, the second argument is the error string associated
294              with the error.  With a background copy, it is not necessary  to
295              put  inputChan  or  outputChan  into non-blocking mode; the chan
296              copy command takes care of that automatically.  However,  it  is
297              necessary  to enter the event loop by using the vwait command or
298              by using Tk.
299
300              You are not allowed to do other I/O operations with inputChan or
301              outputChan  during  a background chan copy.  If either inputChan
302              or outputChan get closed while the copy is in progress, the cur‐
303              rent  copy  is stopped and the command callback is not made.  If
304              inputChan is closed, then all data already queued for outputChan
305              is written out.
306
307              Note  that  inputChan  can  become  readable during a background
308              copy.  You should turn off any chan event or fileevent  handlers
309              during a background copy so those handlers do not interfere with
310              the copy.  Any I/O attempted by a chan event or  fileevent  han‐
311              dler will get a “channel busy” error.
312
313              Chan copy translates end-of-line sequences in inputChan and out‐
314              putChan according to the -translation option for these  channels
315              (see chan configure above).  The translations mean that the num‐
316              ber of bytes read from inputChan can be different than the  num‐
317              ber  of  bytes  written to outputChan.  Only the number of bytes
318              written to outputChan is reported, either as the return value of
319              a  synchronous  chan copy or as the argument to the callback for
320              an asynchronous chan copy.
321
322              Chan copy obeys the encodings and character translations config‐
323              ured  for  the channels. This means that the incoming characters
324              are converted internally first UTF-8 and then into the  encoding
325              of the channel chan copy writes to (see chan configure above for
326              details on the -encoding and -translation options).  No  conver‐
327              sion  is  done  if  both channels are set to encoding binary and
328              have matching translations. If only the output channel is set to
329              encoding  binary the system will write the internal UTF-8 repre‐
330              sentation of the incoming characters. If only the input  channel
331              is set to encoding binary the system will assume that the incom‐
332              ing bytes are valid UTF-8 characters and convert them  according
333              to  the  output  encoding. The behaviour of the system for bytes
334              which are not valid UTF-8 characters is undefined in this case.
335
336       chan create mode cmdPrefix
337              This subcommand creates a new script  level  channel  using  the
338              command  prefix  cmdPrefix  as  its handler. Any such channel is
339              called a reflected channel. The specified command  prefix,  cmd‐
340              Prefix, must be a non-empty list, and should provide the API de‐
341              scribed in the refchan manual page. The handle of the new  chan‐
342              nel  is  returned  as the result of the chan create command, and
343              the channel is open. Use either close or chan  close  to  remove
344              the channel.
345
346              The  argument  mode  specifies  if the new channel is opened for
347              reading, writing, or both. It has to be a list containing any of
348              the  strings “read” or “write”.  The list must have at least one
349              element, as a channel you can neither write  to  nor  read  from
350              makes  no  sense.  The  handler command for the new channel must
351              support the chosen mode, or an error is thrown.
352
353              The command prefix is executed in the global namespace,  at  the
354              top  of  call stack, following the appending of arguments as de‐
355              scribed in the refchan manual page. Command  resolution  happens
356              at  the time of the call. Renaming the command, or destroying it
357              means that the next call of a handler method may  fail,  causing
358              the  channel  command  invoking the handler to fail as well. De‐
359              pending on the subcommand being invoked, the error  message  may
360              not be able to explain the reason for that failure.
361
362              Every  channel  created  with this subcommand knows which inter‐
363              preter it was created in, and only  ever  executes  its  handler
364              command in that interpreter, even if the channel was shared with
365              and/or was moved into a different  interpreter.  Each  reflected
366              channel  also  knows  the thread it was created in, and executes
367              its handler command only in that thread, even if the channel was
368              moved  into  a  different thread. To this end all invocations of
369              the handler are forwarded to the original thread by posting spe‐
370              cial events to it. This means that the original thread (i.e. the
371              thread that executed the chan create command) must have  an  ac‐
372              tive  event  loop,  i.e. it must be able to process such events.
373              Otherwise the thread sending them will block indefinitely. Dead‐
374              lock may occur.
375
376              Note  that this permits the creation of a channel whose two end‐
377              points live in two different threads,  providing  a  stream-ori‐
378              ented  bridge between these threads. In other words, we can pro‐
379              vide a way for regular stream communication between threads  in‐
380              stead of having to send commands.
381
382              When  a  thread  or interpreter is deleted, all channels created
383              with this subcommand and using this thread/interpreter as  their
384              computing  base  are  deleted  as well, in all interpreters they
385              have been shared with or moved into, and in whatever thread they
386              have been transferred to. While this pulls the rug out under the
387              other thread(s) and/or interpreter(s), this cannot  be  avoided.
388              Trying to use such a channel will cause the generation of a reg‐
389              ular error about unknown channel handles.
390
391              This subcommand is safe  and  made  accessible  to  safe  inter‐
392              preters.   While  it arranges for the execution of arbitrary Tcl
393              code the system also makes sure that the code is always executed
394              within the safe interpreter.
395
396       chan eof channelId
397              Test  whether  the  last  input  operation on the channel called
398              channelId failed because the end of the data stream was reached,
399              returning 1 if end-of-file was reached, and 0 otherwise.
400
401       chan event channelId event ?script?
402              Arrange  for  the  Tcl  script  script to be installed as a file
403              event handler to be called whenever the channel called channelId
404              enters  the state described by event (which must be either read‐
405              able or writable); only one such handler may  be  installed  per
406              event per channel at a time.  If script is the empty string, the
407              current handler is deleted (this also happens if the channel  is
408              closed  or  the interpreter deleted).  If script is omitted, the
409              currently installed script is returned (or an empty string if no
410              such  handler  is installed).  The callback is only performed if
411              the event loop is being serviced (e.g. via vwait or update).
412
413              A file event handler is  a  binding  between  a  channel  and  a
414              script,  such  that the script is evaluated whenever the channel
415              becomes readable or writable.  File event handlers are most com‐
416              monly  used to allow data to be received from another process on
417              an event-driven basis, so that the receiver can continue to  in‐
418              teract  with  the  user or with other channels while waiting for
419              the data to arrive.  If an application invokes chan gets or chan
420              read  on  a  blocking channel when there is no input data avail‐
421              able, the process will block; until the input data  arrives,  it
422              will  not  be able to service other events, so it will appear to
423              the user to “freeze up”.  With chan event, the process can  tell
424              when data is present and only invoke chan gets or chan read when
425              they will not block.
426
427              A channel is considered to be readable if there is  unread  data
428              available  on  the underlying device.  A channel is also consid‐
429              ered to be readable if there is unread data in an input  buffer,
430              except in the special case where the most recent attempt to read
431              from the channel was a chan gets call that could not find a com‐
432              plete  line  in the input buffer.  This feature allows a file to
433              be read a line at a time in non-blocking mode using  events.   A
434              channel  is  also considered to be readable if an end of file or
435              error condition is present on the underlying file or device.  It
436              is important for script to check for these conditions and handle
437              them appropriately; for example, if there is  no  special  check
438              for  end  of file, an infinite loop may occur where script reads
439              no data, returns, and is immediately invoked again.
440
441              A channel is considered to be writable if at least one  byte  of
442              data  can  be  written  to the underlying file or device without
443              blocking, or if an error condition is present on the  underlying
444              file or device.  Note that client sockets opened in asynchronous
445              mode become writable when they become connected or if  the  con‐
446              nection fails.
447
448              Event-driven  I/O  works best for channels that have been placed
449              into non-blocking mode with  the  chan  configure  command.   In
450              blocking mode, a chan puts command may block if you give it more
451              data than the underlying file or device can accept, and  a  chan
452              gets or chan read command will block if you attempt to read more
453              data than is ready; no events will be processed while  the  com‐
454              mands  block.   In  non-blocking  mode chan puts, chan read, and
455              chan gets never block.
456
457              The script for a file event is executed at global level (outside
458              the  context  of  any Tcl procedure) in the interpreter in which
459              the chan event command was invoked.  If an  error  occurs  while
460              executing  the  script  then  the command registered with interp
461              bgerror is used to report the  error.   In  addition,  the  file
462              event  handler  is  deleted if it ever returns an error; this is
463              done in order to prevent infinite loops due to buggy handlers.
464
465       chan flush channelId
466              Ensures that all pending output for the channel called channelId
467              is written.
468
469              If  the  channel is in blocking mode the command does not return
470              until all the buffered output has been flushed to  the  channel.
471              If  the  channel is in non-blocking mode, the command may return
472              before all buffered output has been flushed; the remainder  will
473              be  flushed  in the background as fast as the underlying file or
474              device is able to absorb it.
475
476       chan gets channelId ?varName?
477              Reads the next line from the channel called channelId.  If  var‐
478              Name  is  not  specified,  the result of the command will be the
479              line that has been read (without a trailing  newline  character)
480              or an empty string upon end-of-file or, in non-blocking mode, if
481              the data available is exhausted. If varName  is  specified,  the
482              line  that  has been read will be written to the variable called
483              varName and result will be the number of  characters  that  have
484              been  read  or -1 if end-of-file was reached or, in non-blocking
485              mode, if the data available is exhausted.
486
487              If an end-of-file occurs while part way through reading a  line,
488              the  partial  line  will  be returned (or written into varName).
489              When varName is not specified, the end-of-file case can be  dis‐
490              tinguished  from  an  empty line using the chan eof command, and
491              the partial-line-but-non-blocking case can be distinguished with
492              the chan blocked command.
493
494       chan names ?pattern?
495              Produces  a  list of all channel names. If pattern is specified,
496              only those channel names that match it (according to  the  rules
497              of string match) will be returned.
498
499       chan pending mode channelId
500              Depending on whether mode is input or output, returns the number
501              of bytes of input or output  (respectively)  currently  buffered
502              internally  for channelId (especially useful in a readable event
503              callback to impose application-specific  limits  on  input  line
504              lengths  to  avoid  a potential denial-of-service attack where a
505              hostile user crafts an extremely  long  line  that  exceeds  the
506              available  memory  to buffer it).  Returns -1 if the channel was
507              not opened for the mode in question.
508
509       chan pipe
510              Creates a standalone pipe whose read-  and  write-side  channels │
511              are  returned  as  a 2-element list, the first element being the │
512              read side and the second the write side. Can be useful  e.g.  to │
513              redirect  separately  stderr and stdout from a subprocess. To do │
514              this, spawn with "2>@" or ">@" redirection  operators  onto  the │
515              write  side of a pipe, and then immediately close it in the par‐ │
516              ent. This is necessary to get an EOF on the read side  once  the │
517              child has exited or otherwise closed its output.                 │
518
519              Note that the pipe buffering semantics can vary at the operating │
520              system level substantially; it is not  safe  to  assume  that  a │
521              write  performed  on the output side of the pipe will appear in‐ │
522              stantly to the input side. This is a fundamental difference  and │
523              Tcl cannot conceal it. The overall stream semantics are compati‐ │
524              ble, so blocking reads and writes will not see most of the  dif‐ │
525              ferences,  but the details of what exactly gets written when are │
526              not. This is most likely to show up  when  using  pipelines  for │
527              testing;  care  should  be taken to ensure that deadlocks do not │
528              occur and that potential short reads are allowed for.            │
529
530       chan pop channelId
531              Removes the topmost transformation from the  channel  channelId, │
532              if  there is any. If there are no transformations added to chan‐
533              nelId, this is equivalent to chan close of that channel. The re‐ │
534              sult  is  normally the empty string, but can be an error in some │
535              situations (i.e. where the underlying system  stream  is  closed │
536              and that results in an error).
537
538       chan postevent channelId eventSpec
539              This  subcommand is used by command handlers specified with chan
540              create. It notifies the channel represented by the handle  chan‐
541              nelId  that  the event(s) listed in the eventSpec have occurred.
542              The argument has to be a list containing any of the strings read
543              and write. The list must contain at least one element as it does
544              not make sense to invoke the command if there are no  events  to
545              post.
546
547              Note  that this subcommand can only be used with channel handles
548              that were created/opened by chan create. All other channels will
549              cause this subcommand to report an error.
550
551              As  only  the  Tcl level of a channel, i.e. its command handler,
552              should post events to it we also restrict the usage of this com‐
553              mand  to  the  interpreter  that  created  the channel. In other
554              words, posting events to a reflected channel from an interpreter
555              that  does  not  contain it's implementation is not allowed. At‐
556              tempting to post an event from any other interpreter will  cause
557              this subcommand to report an error.
558
559              Another  restriction  is  that it is not possible to post events
560              that the I/O core has not registered an interest in.  Trying  to
561              do  so  will cause the method to throw an error. See the command
562              handler method watch described in refchan, the document specify‐
563              ing the API of command handlers for reflected channels.
564
565              This  command  is safe and made accessible to safe interpreters.
566              It can trigger the execution of chan event handlers, whether  in
567              the  current  interpreter  or  in  other  interpreters  or other
568              threads, even where the event is posted from a safe  interpreter
569              and  listened  for by a trusted interpreter. Chan event handlers
570              are always executed in the interpreter that set them up.
571
572       chan push channelId cmdPrefix
573              Adds a new transformation on top of the channel  channelId.  The │
574              cmdPrefix  argument  describes a list of one or more words which │
575              represent a handler that will be used to implement the transfor‐ │
576              mation. The command prefix must provide the API described in the │
577              transchan manual page.  The result of this subcommand is a  han‐ │
578              dle  to  the  transformation.  Note that it is important to make │
579              sure that the transformation is capable of supporting the  chan‐ │
580              nel  mode that it is used with or this can make the channel nei‐ │
581              ther readable nor writable.
582
583       chan puts ?-nonewline? ?channelId? string
584              Writes string to the channel named channelId followed by a  new‐
585              line  character.  A trailing newline character is written unless
586              the optional flag -nonewline is given. If channelId is  omitted,
587              the string is written to the standard output channel, stdout.
588
589              Newline  characters in the output are translated by chan puts to
590              platform-specific end-of-line sequences according  to  the  cur‐
591              rently configured value of the -translation option for the chan‐
592              nel (for example, on PCs newlines  are  normally  replaced  with
593              carriage-return-linefeed sequences; see chan configure above for
594              details).
595
596              Tcl buffers output internally, so characters written  with  chan
597              puts  may  not  appear immediately on the output file or device;
598              Tcl will normally delay output until the buffer is full  or  the
599              channel  is  closed.  You can force output to appear immediately
600              with the chan flush command.
601
602              When the output buffer fills up, the chan puts command will nor‐
603              mally  block  until  all the buffered data has been accepted for
604              output by the operating system.  If channelId is in non-blocking
605              mode then the chan puts command will not block even if the oper‐
606              ating system cannot accept the data.  Instead, Tcl continues  to
607              buffer  the  data and writes it in the background as fast as the
608              underlying file or device can accept it.  The  application  must
609              use  the  Tcl event loop for non-blocking output to work; other‐
610              wise Tcl never finds out that the file or device  is  ready  for
611              more  output  data.   It  is  possible  for an arbitrarily large
612              amount of data to be buffered  for  a  channel  in  non-blocking
613              mode,  which  could  consume a large amount of memory.  To avoid
614              wasting memory, non-blocking I/O should normally be used  in  an
615              event-driven  fashion with the chan event command (do not invoke
616              chan puts unless you have recently  been  notified  via  a  file
617              event that the channel is ready for more output data).
618
619       chan read channelId ?numChars?
620
621       chan read ?-nonewline? channelId
622              In  the first form, the result will be the next numChars charac‐
623              ters read from the channel named channelId; if numChars is omit‐
624              ted,  all characters up to the point when the channel would sig‐
625              nal a failure (whether an end-of-file, blocked  or  other  error
626              condition)  are read. In the second form (i.e. when numChars has
627              been omitted) the flag -nonewline may be given to indicate  that
628              any  trailing newline in the string that has been read should be
629              trimmed.
630
631              If channelId is in non-blocking mode, chan read may not read  as
632              many  characters as requested: once all available input has been
633              read, the command will return the data that is available  rather
634              than  blocking  for more input.  If the channel is configured to
635              use a multi-byte encoding, then there may actually be some bytes
636              remaining  in  the  internal buffers that do not form a complete
637              character.  These bytes will not be returned  until  a  complete
638              character  is  available or end-of-file is reached.  The -nonew‐
639              line switch is ignored if the command  returns  before  reaching
640              the end of the file.
641
642              Chan  read  translates  end-of-line  sequences in the input into
643              newline characters according to the -translation option for  the
644              channel  (see  chan configure above for a discussion on the ways
645              in which chan configure will alter input).
646
647              When reading from a serial port, most applications  should  con‐
648              figure the serial port channel to be non-blocking, like this:
649
650                     chan configure channelId -blocking 0.
651
652              Then  chan  read  behaves  much like described above.  Note that
653              most serial ports are comparatively slow; it is entirely  possi‐
654              ble  to  get a readable event for each character read from them.
655              Care must be taken when  using  chan  read  on  blocking  serial
656              ports:
657
658              chan read channelId numChars
659                     In  this  form  chan read blocks until numChars have been
660                     received from the serial port.
661
662              chan read channelId
663                     In this form chan read blocks until the reception of  the
664                     end-of-file  character,  see  chan configure -eofchar. If
665                     there no end-of-file character has  been  configured  for
666                     the channel, then chan read will block forever.
667
668       chan seek channelId offset ?origin?
669              Sets  the  current  access  position  within the underlying data
670              stream for the channel named channelId to be offset bytes  rela‐
671              tive  to  origin.  Offset must be an integer (which may be nega‐
672              tive) and origin must be one of the following:
673
674              start     The new access position will be offset bytes from  the
675                        start of the underlying file or device.
676
677              current   The  new access position will be offset bytes from the
678                        current access position; a negative offset  moves  the
679                        access  position  backwards  in the underlying file or
680                        device.
681
682              end       The new access position will be offset bytes from  the
683                        end  of  the file or device.  A negative offset places
684                        the access position before the end of file, and a pos‐
685                        itive  offset places the access position after the end
686                        of file.
687
688              The origin argument defaults to start.
689
690              Chan seek flushes all buffered output for the channel before the
691              command  returns,  even  if the channel is in non-blocking mode.
692              It also discards any buffered and unread  input.   This  command
693              returns an empty string.  An error occurs if this command is ap‐
694              plied to channels whose underlying file or device does not  sup‐
695              port seeking.
696
697              Note that offset values are byte offsets, not character offsets.
698              Both chan seek and chan tell operate  in  terms  of  bytes,  not
699              characters, unlike chan read.
700
701       chan tell channelId
702              Returns  a  number giving the current access position within the
703              underlying data stream for the  channel  named  channelId.  This
704              value  returned is a byte offset that can be passed to chan seek
705              in order to set the channel to a particular position.  Note that
706              this  value is in terms of bytes, not characters like chan read.
707              The value returned is -1 for channels that do not support  seek‐
708              ing.
709
710       chan truncate channelId ?length?
711              Sets the byte length of the underlying data stream for the chan‐
712              nel named channelId to be length (or to the current byte  offset
713              within  the  underlying  data  stream if length is omitted). The
714              channel is flushed before truncation.
715

EXAMPLES

717       This opens a file using a known encoding (CP1252, a very common  encod‐
718       ing  on  Windows), searches for a string, rewrites that part, and trun‐
719       cates the file after a further two lines.
720
721              set f [open somefile.txt r+]
722              chan configure $f -encoding cp1252
723              set offset 0
724
725              # Search for string "FOOBAR" in the file
726              while {[chan gets $f line] >= 0} {
727                  set idx [string first FOOBAR $line]
728                  if {$idx > -1} {
729                      # Found it; rewrite line
730
731                      chan seek $f [expr {$offset + $idx}]
732                      chan puts -nonewline $f BARFOO
733
734                      # Skip to end of following line, and truncate
735                      chan gets $f
736                      chan gets $f
737                      chan truncate $f
738
739                      # Stop searching the file now
740                      break
741                  }
742
743                  # Save offset of start of next line for later
744                  set offset [chan tell $f]
745              }
746              chan close $f
747
748       A network server that does echoing of its  input  line-by-line  without
749       preventing servicing of other connections at the same time.
750
751              # This is a very simple logger...
752              proc log {message} {
753                  chan puts stdout $message
754              }
755
756              # This is called whenever a new client connects to the server
757              proc connect {chan host port} {
758                  set clientName [format <%s:%d> $host $port]
759                  log "connection from $clientName"
760                  chan configure $chan -blocking 0 -buffering line
761                  chan event $chan readable [list echoLine $chan $clientName]
762              }
763
764              # This is called whenever either at least one byte of input
765              # data is available, or the channel was closed by the client.
766              proc echoLine {chan clientName} {
767                  chan gets $chan line
768                  if {[chan eof $chan]} {
769                      log "finishing connection from $clientName"
770                      chan close $chan
771                  } elseif {![chan blocked $chan]} {
772                      # Didn't block waiting for end-of-line
773                      log "$clientName - $line"
774                      chan puts $chan $line
775                  }
776              }
777
778              # Create the server socket and enter the event-loop to wait
779              # for incoming connections...
780              socket -server connect 12345
781              vwait forever
782

SEE ALSO

784       close(n),   eof(n),   fblocked(n),  fconfigure(n),  fcopy(n),  file(n),
785       fileevent(n), flush(n), gets(n), open(n),  puts(n),  read(n),  seek(n),
786       socket(n), tell(n), refchan(n), transchan(n)
787

KEYWORDS

789       channel, input, output, events, offset
790
791
792
793Tcl                                   8.5                              chan(n)
Impressum