Tcl running processes
last modified November 24, 2026 Tcl 8.6
A Tcl script does not have to do all the work itself. System tools such as
sort, grep, ssh or a compiler already
solve many problems well, and Tcl can start them, feed them and read their
answers. This is one of the reasons Tcl is popular for build scripts, test
harnesses and system administration: the language is small, while the operating
system provides the heavy machinery.
Two commands carry most of that work. The exec command runs a
program, waits for it to finish and returns what it printed. The
open command with a leading pipe starts a program too, but gives
back a channel that can be read line by line. This article follows both, then
looks at exit statuses, pipelines, environment variables, process identifiers
and background jobs.
Running a command with exec
The exec command takes the name of a program followed
by its arguments, starts the program and waits for it. The value of
exec is the standard output of the child, with one trailing newline
removed. Because the result is an ordinary Tcl value, it can be stored in a
variable, compared, or placed inside a larger string.
set host [exec hostname] puts "Host: $host" set user [exec whoami] puts "User: $user" set kernel [exec uname -r] puts "Kernel: $kernel"
Each line is a complete command: exec receives the program name and
its arguments as separate words, so no shell parses the line. Wildcards,
redirections and pipes written inside a word are not interpreted by a shell;
Tcl itself handles the cases it supports. The three variables hold plain text
that can be printed or processed further.
$ tclsh exec_intro.tcl Host: universum User: jano Kernel: 6.8.0-149-generic
Capturing output as lines
Programs usually print several lines, and exec keeps them in one
string with the newline characters still inside. Only the final newline is
dropped, which is convenient for a single value but hides the number of lines.
The -keepnewline option switches that trimming off, and
split turns the text into a list of lines.
set plain [exec printf "alpha\nbeta\ngamma\n"]
puts "plain length: [string length $plain]"
set kept [exec -keepnewline printf "alpha\nbeta\ngamma\n"]
puts "kept length: [string length $kept]"
foreach line [split $plain "\n"] {
puts "line: $line"
}
The text alpha beta gamma with two separating newlines is 16
characters long, so plain length reports 16 while
kept length reports 17 with the trailing newline included. The
foreach loop walks the split list and prints one line per element.
Tcl escapes such as \n are substituted before the child program
runs, so printf receives real newlines.
$ tclsh capture_lines.tcl plain length: 16 kept length: 17 line: alpha line: beta line: gamma
Exit status and standard error
Commands on Unix report success or failure through an exit status: zero means
success and anything else means a problem. The exec command turns
a non-zero status into a Tcl error, and it does the same when a child writes to
standard error, even if the status is zero. A script that wants to inspect a
failure instead of stopping has to wrap the call in catch, which returns a code and stores the message and
the error options.
puts "quiet success: '[exec true]'"
set rc [catch {exec sh -c {echo "warning: old config" >&2}} warning]
puts "stderr only, exit 0 -> code $rc: $warning"
set rc [catch {exec sh -c {echo "warning: old config" >&2} 2>@1} note]
puts "redirected with 2>@1 -> code $rc: $note"
set rc [catch {exec sh -c {echo "step one"; echo "disk full" >&2; exit 2}} result options]
puts "failed command -> code $rc"
puts "message:"
puts $result
puts "exit code: [lindex [dict get $options -errorcode] 2]"
The first line shows that a successful command returns an empty string. The
second call writes only to standard error and still raises an error, which is
why the warning text arrives as the message. Adding the redirection
2>@1 sends standard error into standard output, so the same text
becomes normal output and the call succeeds. In the last block the child exits
with status 2; the -errorcode option holds a list whose first
element is CHILDSTATUS, followed by the child process id and the
numeric status, which is why lindex ... 2 extracts the 2.
$ tclsh exit_status.tcl quiet success: '' stderr only, exit 0 -> code 1: warning: old config redirected with 2>@1 -> code 0: warning: old config failed command -> code 1 message: step one disk full exit code: 2
Pipelines
A vertical bar between two commands in an exec call connects them
the way a shell does: the standard output of the left command becomes the
standard input of the right one. Several stages can follow each other. The value
of the whole call is the output of the last stage only, because Tcl has no
useful place to put the earlier ones.
set words {pear apple fig apple}
set text [join $words "\n"]
set counts [exec printf "%s\n" $text | sort | uniq -c | sort -rn]
puts "counts:"
puts $counts
set first [lindex [split [string trim $counts] "\n"] 0]
puts "most common: [string trim $first]"
The list of fruit is joined into one multi-line string and handed to
printf, which prints it unchanged. sort orders the
lines, uniq -c counts equal neighbours and the second
sort orders the counts from the largest. The last two lines take
the first line of the result and trim the padding that uniq adds.
Every stage is a separate process, started and reaped by Tcl.
$ tclsh pipelines.tcl
counts:
2 apple
1 pear
1 fig
most common: 2 apple
Opening a pipeline channel
Waiting for a command to finish is fine for short tools, but a compiler, a long download or a log producer runs for minutes. The open command accepts a leading pipe and returns a channel instead of a value, so the script can read the output while the child is still running. Reading is done with gets in a loop, and close finishes the child and reports whether it succeeded.
set ch [open {|sh -c "printf 'line one\nline two\nline three\n'"} r]
set count 0
while {[gets $ch line] >= 0} {
incr count
puts "$count: $line"
}
set status [close $ch]
puts "closed with status '$status'"
set bad [open {|sh -c "echo partial output; exit 5"} r]
puts "read: [string trim [read $bad]]"
puts "close raised: [catch {close $bad} msg] $msg"
The channel is opened for reading and consumed one line at a time, which keeps
memory flat for long outputs. gets returns the number of characters
read, or -1 at end of file, and that is why the loop compares against zero.
Closing a successful pipeline returns an empty string. The second half shows the
opposite case: all the output can be read, but close raises an error
because the child exited with status 5, so the failure is noticed at the end of
the stream rather than silently ignored.
$ tclsh pipeline_channel.tcl 1: line one 2: line two 3: line three closed with status '' read: partial output close raised: 1 child process exited abnormally
Environment variables
The environment a process inherits is exposed as the global array
env. Reading $env(PATH) gives the search path, and
assigning to an element changes the environment of every child started
afterwards. Removing a variable with unset hides it from later
children. Because the array may be missing entries, a careful script checks with
info exists before reading.
puts "PATH is [expr {[info exists env(PATH)] ? "set" : "missing"}]"
puts "APP_MODE before: [expr {[info exists env(APP_MODE)] ? $env(APP_MODE) : "not set"}]"
set env(APP_MODE) "testing"
puts "child sees APP_MODE=[exec printenv APP_MODE]"
unset env(APP_MODE)
puts "after unset: [exec sh -c {echo ${APP_MODE:-not set}}]"
The first line tests for the usual search path variable. The second one prints
the value of APP_MODE only if it exists, which avoids an error when
the variable was never set. Setting the array element makes the value visible
to printenv in the child, and after unset the shell in
the last line falls back to its default. No Tcl function is needed to export a
variable; the array is the environment.
$ tclsh env_demo.tcl PATH is set APP_MODE before: not set child sees APP_MODE=testing after unset: not set
Process identifiers
Every running process has a numeric identifier, and Tcl exposes two of them. The
pid command without arguments returns the identifier of
the interpreter itself. Given a channel that was opened with a pipe,
pid returns the identifier of the child process, which is what a
supervisor script needs in order to check or stop a job.
puts "this script runs as pid [pid]"
set ch [open {|sleep 0.3} r]
set child [pid $ch]
puts "child command pid: $child"
if {[catch {exec kill -0 $child}] == 0} {
puts "child is still running"
}
close $ch
puts "child has finished"
The child sleeps for three tenths of a second, so it is alive when
kill -0 is called; that signal zero form only tests for existence
and does not stop anything. close then waits for the child, which
is why the last message arrives after the pause. The concrete numbers differ on
every run and on every machine.
$ tclsh pids.tcl this script runs as pid 34628 child command pid: 34629 child is still running child has finished
Background jobs
Sometimes a script should start a helper and continue immediately. Putting an
ampersand as the last argument of exec asks Tcl to start the command
in the background and return at once. The child inherits the standard channels,
so its output appears on the same terminal, and the script gets no channel for
reading it and no status when it ends.
puts "main: starting the job"
exec sh -c {sleep 0.2; echo "job: report is ready"} &
puts "main: did not wait for the job"
after 600 {set finished 1}
vwait finished
puts "main: event loop finished"
The script prints two lines without waiting, and the job prints its own line a
fifth of a second later. The after and vwait pair keeps the interpreter alive for 600
milliseconds so the output is not cut off when tclsh exits. When
the script needs the output or the exit status of the job, the pipe form from
the previous section is the better choice, because it gives a channel to read
and a status to check.
$ tclsh background_job.tcl main: starting the job main: did not wait for the job job: report is ready main: event loop finished
Combining Tcl with shell tools safely
The fact that exec does not pass the line through a shell is a
safety feature. A filename containing spaces, quotes, a semicolon or an
ampersand stays one argument, because Tcl already split the command into words
and the child receives them as a list. Trouble starts when a script builds a
shell command string and hands it to sh -c, because the shell then
interprets the value a second time.
set title {Report on "sales" & costs}
puts "as one argument:"
puts [exec printf "title=<%s>\n" $title]
set rc [catch {exec sh -c "echo $title"} out]
puts "through a shell string: code $rc"
puts "output: $out"
puts "through sh -c with a parameter:"
puts [exec sh -c {printf "title=<%s>\n" "$1"} sh $title]
The direct call prints the title exactly as it was stored, including the quotes
and the ampersand. The middle block interpolates the title into a shell command:
the shell ends the echo at the ampersand, runs it in the background
and then tries to execute a program called costs, which fails.
The last call keeps the shell script constant and passes the value as
$1, so the shell never parses the title as syntax. Build command
lists with list rather than strings, and prefer a direct
exec whenever a shell is not required.
$ tclsh shell_safe.tcl as one argument: title=<Report on "sales" & costs> through a shell string: code 1 output: Report on sales sh: 1: costs: not found through sh -c with a parameter: title=<Report on "sales" & costs>
Source
The Tcl 8.6 manual documents exec in full, including the
redirection operators used above, and the open page describes
pipeline channels and their options.
This article showed how Tcl starts and talks to other programs: exec
for short commands and their output, redirects for exit status and standard
error, pipelines for composing tools, pipe channels for long-running jobs, and
the env array for their environment. The exec
command page lists the remaining options, and the event loop article explains how a script stays alive
while a background job works.
Author
List all Tcl Tutorials.