ptolemy.actor.lib
Class Exec

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.actor.lib.Source
                              extended by ptolemy.actor.lib.LimitedFiringSource
                                  extended by ptolemy.actor.lib.Exec
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class Exec
extends LimitedFiringSource

Execute a command as a separately running subprocess.

To get the effect of executing, a command provided in a shell interpreter, prependPlatformDependentShellCommand parameter to true, or set command to "cmd" (Windows) or "sh" (Windows with Cygwin or Linux), and then provide commands at the input port. Note that each command must be terminated with a newline. For example, to open a model in vergil and run it, you can set command to "sh" and use a Const actor to provide on the input port the string:

 "vergil -run model.xml\n exit\n"
 

This actor uses java.lang.Runtime.exec() to invoke a subprocess named by the command parameter in a directory with an environment. Data from the input port (if any) is passed to the input of the subprocess. The subprocess is run until it exits and then contents of the output and error streams of the subprocess (if any) are passed to the output and error ports.

If the subprocess generates no data on the output or error stream, then the data on the corresponding port(s) will consist of the empty string.

A much more interesting actor could be written using a Kahn Process Network. This actor would generate output asynchronously as the process was executing.

For information about Runtime.exec(), see:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

and

http://mindprod.com/jgloss/exec.html

Since:
Ptolemy II 4.0
Version:
$Id: Exec.java 59167 2010-09-21 17:08:02Z cxh $
Author:
Christopher Hylands Brooks, Contributors: Edward A. Lee, Daniel Crawl
See Also:
Serialized Form
Accepted Rating:
Yellow (cxh) 2/24/04
Proposed Rating:
Yellow (cxh) 2/5/04

Nested Class Summary
private  class Exec._StreamReaderThread
           
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  Exec._StreamReaderThread _errorGobbler
           
private  java.io.BufferedWriter _inputBufferedWriter
           
private  Exec._StreamReaderThread _outputGobbler
           
private  java.lang.Process _process
           
private  boolean _stopFireRequested
           
private static int _streamReaderThreadCount
           
 PortParameter command
          The command to be executed.
 FileParameter directory
          The directory in which to execute the command.
 Parameter environment
          The environment in which to execute the command.
 TypedIOPort error
          Data that is generated by the subprocess on its standard error.
 TypedIOPort exitCode
          The exit code of the subprocess.
 TypedIOPort input
          Strings to pass to the standard input of the subprocess.
 Parameter prependPlatformDependentShellCommand
          If true, then prepend the platform dependent shell command to the parsed value of the command parameter.
 Parameter throwExceptionOnNonZeroReturn
          If true, then throw an exception if the subprocess returns non-zero.
 Parameter waitForProcess
          If true, then actor will wait until subprocess completes.
 
Fields inherited from class ptolemy.actor.lib.LimitedFiringSource
_firingCountLimit, _iterationCount, firingCountLimit
 
Fields inherited from class ptolemy.actor.lib.Source
output, trigger
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
Exec(CompositeEntity container, java.lang.String name)
          Construct an actor with the given container and name.
 
Method Summary
private  void _exec()
           
private  java.util.List<java.lang.String> _getCommandList()
          Get the command list arguments for exec.
private  void _terminateProcess()
           
 void fire()
          Invoke a subprocess, read the input data (if any) and wait for the subprocess to terminate before sending any output or error data to the appropriate ports.
 void stop()
          Override the base class and terminate the process.
 void stopFire()
          Override the base class to stop waiting for input data.
 void wrapup()
          Terminate the subprocess.
 
Methods inherited from class ptolemy.actor.lib.LimitedFiringSource
attributeChanged, initialize, postfire
 
Methods inherited from class ptolemy.actor.lib.Source
prefire
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, clone, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, preinitialize, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, terminate
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, preinitialize, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

command

public PortParameter command
The command to be executed. The command is parsed by StringUtilities.tokenizeForExec(String) into tokens and then executed as a separate subprocess. The initial default value is the string echo "Hello, world.".

The command parameter is read only once during fire(). If you want to spawn another different command, use life cycle management actors such RunCompositeActor.


directory

public FileParameter directory
The directory in which to execute the command. This parameter is read each time the subprocess is started in fire(). Once the subprocess is running, this parameter is not read again until fire() is called again.

The initial default value of this parameter $CWD, which corresponds with the value of the Java virtual machine user.dir property which is the user's current working directory. Note that if we are running inside a menu launched application, then ptolemy.actor.gui.jnlp.MenuApplication will change user.dir to be the value of user.home, which is the name of the user's home directory.


environment

public Parameter environment
The environment in which to execute the command. This parameter is read each time the subprocess is started in fire(). Once the subprocess is running, this parameter is not read again until fire() is called again.

This parameter is an array of records that name an environment variable and the value for the value. The format is:

  {{name = "NAME1", value = "value1"}...}
  
Where NAME1 is the name of the environment variable, and value1 is the value.

For example {{name = "PTII", value = "c:/ptII"}} would set the value of the PTII to c:/ptII.

If the initial value of the parameter is {{name="", value = ""}}, then the environment from the calling or parent process is used in the new command.

Note that if this parameter sets any environment variable, then under Windows the other environment variables in the calling or parent process might not be passed to the subprocess. This behaviour could be platform or JVM dependent. When in doubt, try setting the command value to "env" to print out the environment.


error

public TypedIOPort error
Data that is generated by the subprocess on its standard error. While the process is running, any error data generated by the subprocess is stored until the subprocess exits and then the stored error data is sent to the error port. If the subprocess generates no data on standard error, then the empty string (a string of length zero) is generated. This port is an output port of type String.


exitCode

public TypedIOPort exitCode
The exit code of the subprocess. Usually, a non-zero exit code indicate that the subprocess had a problem. This port is an output port of type int.


input

public TypedIOPort input
Strings to pass to the standard input of the subprocess. Note that a newline is not appended to the string. If you require a newline, add one using the AddSubtract actor. This port is an input port of type String.


prependPlatformDependentShellCommand

public Parameter prependPlatformDependentShellCommand
If true, then prepend the platform dependent shell command to the parsed value of the command parameter. By setting this argument to true, it is possible to invoke commands in a platform neutral method.

Under Windows NT or XP, the arguments "cmd.exe" and "/C" are prepended. Under Windows 95, the arguments "command.com" and "/C" are prepended. Under all other platforms, the arguments "/bin/sh" and "-c" are prepended.

By prepending sh or cmd, then this actor can use the file redirection operations.

The default value of this parameter is a boolean of value false, which allows the user to arbitrarily invoke /bin/sh scripts on all platforms.


throwExceptionOnNonZeroReturn

public Parameter throwExceptionOnNonZeroReturn
If true, then throw an exception if the subprocess returns non-zero. The default is a boolean of value true. This parameter is ignored if waitForProcess is false.


waitForProcess

public Parameter waitForProcess
If true, then actor will wait until subprocess completes. The default is a boolean of value true.


_inputBufferedWriter

private java.io.BufferedWriter _inputBufferedWriter

_errorGobbler

private Exec._StreamReaderThread _errorGobbler

_outputGobbler

private Exec._StreamReaderThread _outputGobbler

_process

private java.lang.Process _process

_stopFireRequested

private boolean _stopFireRequested

_streamReaderThreadCount

private static int _streamReaderThreadCount
Constructor Detail

Exec

public Exec(CompositeEntity container,
            java.lang.String name)
     throws NameDuplicationException,
            IllegalActionException
Construct an actor with the given container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the actor cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

fire

public void fire()
          throws IllegalActionException
Invoke a subprocess, read the input data (if any) and wait for the subprocess to terminate before sending any output or error data to the appropriate ports.

If there is no data on the input port, then the subprocess executes without reading any input. If there is no output or error data from the subprocess, then the empty string is sent to the appropriate port(s).

Specified by:
fire in interface Executable
Overrides:
fire in class Source
Throws:
IllegalActionException - If the subprocess cannot be started, if the input of the subprocess cannot be written, if the subprocess gets interrupted, or if the return value of the process is non-zero.

stop

public void stop()
Override the base class and terminate the process.

Specified by:
stop in interface Executable
Overrides:
stop in class AtomicActor

stopFire

public void stopFire()
Override the base class to stop waiting for input data.

Specified by:
stopFire in interface Executable
Overrides:
stopFire in class AtomicActor

wrapup

public void wrapup()
            throws IllegalActionException
Terminate the subprocess. This method is invoked exactly once per execution of an application. None of the other action methods should be be invoked after it.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class AtomicActor
Throws:
IllegalActionException - Not thrown in this base class.

_exec

private void _exec()
            throws IllegalActionException
Throws:
IllegalActionException

_getCommandList

private java.util.List<java.lang.String> _getCommandList()
Get the command list arguments for exec.


_terminateProcess

private void _terminateProcess()