Next: , Previous: Gforth Files, Up: Gforth Environment


2.6 Gforth in pipes

Gforth can be used in pipes created elsewhere (described here). It can also create pipes on its own (see Pipes).

If you pipe into Gforth, your program should read with read-file or read-line from stdin (see General files). Key does not recognize the end of input. Words like accept echo the input and are therefore usually not useful for reading from a pipe. You have to invoke the Forth program with an OS command-line option, as you have no chance to use the Forth command line (the text interpreter would try to interpret the pipe input).

You can output to a pipe with type, emit, cr etc.

When you write to a pipe that has been closed at the other end, Gforth receives a SIGPIPE signal (“pipe broken”). Gforth translates this into the exception broken-pipe-error. If your application does not catch that exception, the system catches it and exits, usually silently (unless you were working on the Forth command line; then it prints an error message and exits). This is usually the desired behaviour.

If you do not like this behaviour, you have to catch the exception yourself, and react to it.

Here's an example of an invocation of Gforth that is usable in a pipe:

     gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
      type repeat ; foo bye"

This example just copies the input verbatim to the output. A very simple pipe containing this example looks like this:

     cat startup.fs |
     gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
      type repeat ; foo bye"|
     head

Pipes involving Gforth's stderr output do not work.