\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#240: An Ensemble Command to Manage Processes}
\date{February 22, 2005}
\author{Steve Bold}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#240}&\textbf{An Ensemble Command to Manage Processes}\\\hline
Author&

Steve Bold \tipmail{stevebold}{hotmail.com}
\\
Created&Tuesday, \(\text{22}^{\text{nd}}\) February 2005\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.14 $\\
Keywords&Tcl\\
Obsoletes&88\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes some new commands through which Tcl scripts can create and monitor child processes.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

This TIP is intended to overcome the following limitations of the existing \textbf{exec} and \textbf{open} commands:
\begin{enumerate}
\item{}
While the stderr stream of a child process can be redirected to a file, it cannot be directed to a pipe and so cannot be captured progressively as the process runs. \cite{tip202} has partially addressed this issue but only for the case where the child's stderr stream is directed to the same pipe as its stdout stream. Independent progressive capture of both stdout and stderr is still not possible.
\setcounter{enumi}{1}
\item{}
In the (admittedly rare) case that a program has a significant delay between closing its standard streams and the process itself terminating, a Tcl script running that program as a background process cannot determine the exit status without blocking until the process terminates.
\setcounter{enumi}{2}
\item{}
The existing \textbf{exec} and \textbf{open} commands impose a special interpretation on the characters \textit{\tiplangle{}\tiprangle{}\tipbar{}\&}. This causes two kinds of problems:
\begin{itemize}
\item{}
scripts wishing to invoke a command on a remote computer using an \textit{rsh} or similar command will sometimes wish to have characters such as \textit{\tiplangle{}\tiprangle{}\tipbar{}\&} interpreted on the remote machine
\item{}
scripts may pass a user entered string as an argument to exec. Such scripts may break unexpectedly if the comment string contains one of the special characters. Such problems could be considered a security weakness in Tcl.
\end{itemize}
\setcounter{enumi}{3}
\item{}
Multiple child processes can be launched together with pipes used to link the streams of adjacent processes. However, little flexibility is provided in such cases, for example you can only capture the exit status of the last process in the pipeline.
\end{enumerate}

A more general problem is that each process related command is a separate top-level command. This is inconsistent with much else in Tcl, makes it harder to find the related commands in some forms of documentation and increases the risk of name clashes as new process related commands are introduced.

The BLT toolkit contains the command \textbf{bgexec} which addresses items (1) and (2) in the above list. However, the resulting implementation is complex and does not appear easy to transfer to the Tcl core. In addition, it is not clear to the author how \textbf{bgexec} could be extended to address items (3) and (4).

A variety of other approaches to addressing these problems are listed on the Wiki [\url{http://wiki.tcl.tk/1353}]. This suggests that it may be difficult to achieve a consensus on what the ideal command(s) for launching processes should look like. This TIP provides a basis through which many of these approaches could be implemented in pure Tcl. The commands specified in this TIP map easily onto the existing low level process related functions in the Tcl core, so the implementation cost is low.

\section{Specification}

There shall be a new ensemble command, \textbf{process}, with at least four subcommands.
\begin{enumerate}
\item{}
The sub-command \textbf{invoke} takes 4 arguments and invokes a sub-process, returning the process id of the child process. The arguments are (in order):
\begin{itemize}
\item{}
a list containing the program name invoke and its arguments
\item{}
a channel to be connected to the stdin stream of the child process (or an empty string if the channel is to be disconnected in the child process).
\item{}
a channel to be connected to the stdout stream of the child process (or an empty string if the channel is to be disconnected in the child process).
\item{}
a channel to be connected to the stderr stream of the child process (or an empty string if the channel is to be disconnected in the child process).
\end{itemize}
\setcounter{enumi}{1}
\item{}
The sub-command \textbf{pipe} takes no arguments and returns a two element list containing the input and output channels of the pipe in that order.
\setcounter{enumi}{2}
\item{}
The sub-command \textbf{status} takes a single argument which is a process id and returns a two element list. The first element is either \textit{running} or \textit{completed} The second element is the exit status of the process.

A process will report an arbitrary exit status of zero while it is running.
\setcounter{enumi}{3}
\item{}
The sub-command \textbf{wait} is similar to \textbf{status} but blocks until the child process has completed.
\end{enumerate}

\section{Examples}

The following shows how the commands proposed here can be used to produce a \textbf{bgexec} like command in pure Tcl. Not all the \textbf{bgexec} options are included and the implementation lacks the error handling needed for a robust implementation.
\begingroup\small\begin{verbatim}
proc bgExecCloseHandler {pid cmd} {
   lassign [process status $pid] status exitCode
   if {$status eq "running"} {
      puts "... deferring close handling for $pid"
      after 1000 [list bgExecCloseHandler $pid $cmd]
   } else {
      if {$cmd ne ""} {
         {expand}$cmd $pid $exitCode
      }
   }
}

proc bgExecReadHandler {chan cmd} {
   if {[gets $chan line] == -1} {
      close $chan
      
      if {[info exists ::bgExecCloseInfo($chan)]} {
         lassign $::bgExecCloseInfo($chan) pid cmd
         after 0 bgExecCloseHandler $pid $cmd
         unset ::bgExecCloseInfo($chan)
      }
   } else {
      {expand}$cmd $line
   }
}

proc bgExecLike {args} {
   set outChan ""; set errChan ""
   set i 0
   set exitCmd ""; set parentOutChan ""
   while {$i != [llength $args]} {
      set arg [lindex $args $i]
      switch -glob -- $arg {
      	
      	-onoutput {
      	   incr i
      	   set cmd [lindex $args $i]
      	   lassign [process pipe] parentChan outChan
      	   fileevent $parentChan readable [list \
                  bgExecReadHandler $parentChan $cmd]
      	   set outCmd $cmd
      	   set parentOutChan $parentChan
      	}
      	
      	-onerror {
      	   incr i
      	   set cmd [lindex $args $i]
      	   lassign [process pipe] parentChan errChan
      	   fileevent $parentChan readable [list \
                  bgExecReadHandler $parentChan $cmd]
      	}
      	
      	-onexit {
      	   incr i
      	   set exitCmd [lindex $args $i]
      	}
      	
      	-* {
      	   error "Unknown switch $arg"
      	}
      	
      	* {
      	   break
      	}
      }
      incr i
   }
   
   set cmdLine [lrange $args $i end]

   # puts [list process invoke $cmdLine "" $outChan $errChan]
   set pid [process invoke $cmdLine "" $outChan $errChan]

   # Close the child end of the pipes - if we opened them.
   foreach var {outChan errChan} {
      if {[set $var] ne ""} {
         close [set $var]
      }
   }
   
   if {$parentOutChan eq ""} {
      # Poll for child process exit then notify client, or at least
      # clean up the zombie.
      after 0 bgExecCloseHandler $pid $exitCmd
   } else {
      # We copy BLT's trick of deferring polling till the stdout pipe
      # closes. This is marginally more efficient, more importantly
      # it stops clients being notified of their process until at stdout
      # channel has closed.
      set ::bgExecCloseInfo($parentOutChan) [list $pid $exitCmd]
   }   
}


# now show bgExecLike in action ...

proc showExit {pid code} {
   puts "$pid terminated with code $code"
}

proc showLine {channel line} {
   puts "$channel: $line"
}

proc runLs {args} {
   puts "invoking ls on $args"
   bgExecLike -onoutput "showLine stdout" -onerror "showLine stderr" \
           -onexit showExit ls {expand}$args
}

# Sample invocations: note when running under tclsh, there is no event loop,
# use 'update' to see the output to see what's happening.

# successful listing
runLs .

# Unsuccessful listing
runLs not-found

# Listing of (non existent) files containing exec/open meta characters
runLs < > | &
\end{verbatim}
\endgroup

\section{Limitations}
\begin{enumerate}
\item{}
For convenient use, the functionality proposed here needs to be supplemented with additional commands providing a higher level interface, perhaps one of them being similar to the \textbf{bgExecLike} example given previously. The author has decided to omit this feature from the TIP because:
\begin{itemize}
\item{}
such commands can be implemented in pure Tcl using the commands described here
\item{}
the exact nature of the high level commands may produce lengthy discussions
\item{}
it could even be argued that such commands are more appropriate in tcllib rather than the Tcl core
\end{itemize}
\setcounter{enumi}{1}
\item{}
As with the current implementation of \textbf{exec}, each channel passed to \textbf{process invoke} must have a valid underlying OS file handle. Consequently when running on Windows:
\begin{itemize}
\item{}
use of a wish standard channel will be immediately rejected
\item{}
use of a socket will be accepted but will trigger an error in the child process.
\end{itemize}
\setcounter{enumi}{2}
\item{}
Efficiency --- The author has not yet attempted a detailed performance study, but this proposal does have some theoretical inefficiencies when compared to a pure C implementation, such as \textbf{bgexec}:
\begin{itemize}
\item{}
an intermediate Tcl procedure is used to capture output from a pipe
\item{}
each end of each pipe has to be wrapped in a \textit{CommandChannel} before it can be passed back to the calling script, even if the pipe is just going to be used to link together two processes in a pipeline.
\end{itemize}
\end{enumerate}

\section{Related Possibilities for Future Enhancements}
\begin{enumerate}
\item{}
For Windows, an important limitation that is not addressed by this TIP, is the lack of control over the console window settings when invoking a process. This will require changes to \textit{TclpCreateProcess}.
\setcounter{enumi}{1}
\item{}
A \textbf{kill} subcommand would be a useful addition to the \textbf{process} ensemble. On Windows, the ability to kill a child console process cleanly is related to the choice of console mode, so this issue would ideally be addressed in conjunction with item (1) above.
\setcounter{enumi}{2}
\item{}
A command to categorise an exit status obtained from \textbf{process status} or \textbf{process wait} along similar lines to the data placed in \textit{\$errorCode} by \textit{TclCleanupChildren()}.
\setcounter{enumi}{3}
\item{}
Some aspects of the existing \textbf{exec} command depend on use of temporary files. Since this TIP transfers the high level implementation of process launching into Tcl scripts, support for creation of uniquely named temporary files, as proposed in \cite{tip210}, would be useful.
\setcounter{enumi}{4}
\item{}
The wish console on Windows could be improved, using this mechanism, so that program names typed interactively will run in the background, allowing output to be seen before the process completes.
\setcounter{enumi}{5}
\item{}
The ability to define \textit{argv[0]}, independently from the program name, would occasionally be useful. For example, some UNIX shells run as login shells when \textit{argv[0]} begins with a dash.
\setcounter{enumi}{6}
\item{}
Public C functions for invoking a process and creating a pipe wrapped in command channels.
\setcounter{enumi}{7}
\item{}
Support for detaching process and for reaping detached processes.
\setcounter{enumi}{8}
\item{}
The existing \textbf{exit} command could be duplicated in the \textbf{process} ensemble.
\setcounter{enumi}{9}
\item{}
The basic form of the existing \textbf{pid} command, which obtains the process id of the current process, could be added to the \textbf{process} ensemble.
\setcounter{enumi}{10}
\item{}
In some cases, it is more appropriate to run a child process with its streams connected to a null file rather than disconnected. Since the name of the null file is platform specific, it would be helpful to have a platform independent way of accessing the name.
\setcounter{enumi}{11}
\item{}
An option to obtain full status information. On Windows, process exit codes are 32 bit. On UNIX, higher bits of a waitpid() status value distinguish termination via exit() from termination via an uncaught signal.
\end{enumerate}

\section{Reference Implementation}

Submitted as patch 1315115 [\url{https://sourceforge.net/support/tracker.php?aid=1315115}]

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#2}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#202]{tip202}
Jeff Hobbs,
\emph{Add 2\tiprangle{}@1 Special Case to [open] and [exec]},
on-line at \url{http://purl.org/tcl/tip/202.html}
\bibitem[TIP \#210]{tip210}
Bob Techentin,
Donal K. Fellows,
\emph{Add 'tempfile' Subcommand to 'file'},
on-line at \url{http://purl.org/tcl/tip/210.html}
\end{thebibliography}
\end{document}
