org.kde.koala

Class KProcess

public class KProcess extends QObject

Child process invocation, monitoring and control.
  • General usage and features:
  • This class allows a KDE application to start child processes without having to worry about UNX signal handling issues and zombie process reaping. Basically, this class distinguishes three different ways of running child processes:
  • DontCare -- The child process is invoked and both the child process and the parent process continue concurrently.
  • The process is started in an own session (see setsid(2)).
  • NotifyOnExit -- The child process is invoked and both the child and the parent process run concurrently.
  • When the child process exits, the KProcess instance corresponding to it emits the Qt signal processExited(). Since this signal is not emitted from within a UNX signal handler, arbitrary function calls can be made. Be aware: When the KProcess object gets destructed, the child process will be killed if it is still running! This means in particular, that it usually makes no sense to use a KProcess on the stack with NotifyOnExit.
  • OwnGroup -- like NotifyOnExit, but the child process is started in an own process group (and an own session, FWIW). The behavior of kill() changes to killing the whole process group - this makes this mode useful for implementing primitive job management. It can be used to work around broken wrapper scripts that don't propagate signals to the "real" program. However, use this with care, as you disturb the shell's job management if your program is started from the command line.
  • Block -- The child process starts and the parent process is suspended until the child process exits. (Really not recommended for programs with a GUI.) In this mode the parent can read the child's output, but can't send it any input.
  • KProcess also provides several functions for determining the exit status and the pid of the child process it represents. Furthermore it is possible to supply command-line arguments to the process in a clean fashion (no null-terminated stringlists and such...) A small usage example:
       KProcess proc = new KProcess;
       proc << "my_executable";
       proc << "These" << "are" << "the" << "command" << "line" << "args";
       QApplication.connect(proc, SIGNAL("processExited(KProcess )"),
                             pointer_to_my_object, SLOT("my_objects_slot(KProcess )"));
       proc.start();
     
    This will start "my_executable" with the commandline arguments "These"... When the child process exits, the slot will be invoked.
  • Communication with the child process:
  • KProcess supports communication with the child process through stdin/stdout/stderr. The following functions are provided for getting data from the child process or sending data to the child's stdin (For more information, have a look at the documentation of each function):
  • writeStdin() -- Transmit data to the child process' stdin. When all data was sent, the signal wroteStdin() is emitted.
  • When data arrives at stdout or stderr, the signal receivedStdout() resp. receivedStderr() is emitted.
  • You can shut down individual communication channels with closeStdin(), closeStdout(), and closeStderr(), resp.
  • See KProcessSignals for signals emitted by KProcess

    Author: Christian Czezatke e9025461@student.tuwien.ac.at

    See Also: KProcIO

    UNKNOWN: Child process invocation, monitoring and control.

    Field Summary
    static intAll
    static intAllOutput
    static intBlock
    static intDontCare
    Run-modes for a child process.
    static intNoCommunication
    Modes in which the communication channel can be opened.
    static intNoRead
    static intNotifyOnExit
    static intOwnGroup
    static intPrioHigh
    static intPrioHigher
    static intPrioHighest
    static intPrioLow
    static intPrioLower
    static intPrioLowest
    More or less intuitive constants for use with setPriority().
    static intPrioNormal
    static intStderr
    static intStdin
    static intStdout
    Constructor Summary
    protected KProcess(Class dummy)
    KProcess(QObject parent, String name)
    Constructor
    KProcess(QObject parent)
    KProcess()
    Constructor
    Method Summary
    protected intchildError(int fdno)
    Called by slotChildError() this function copies data arriving from the child process' stderr to the respective buffer and emits the signal receivedStderr().
    protected intchildOutput(int fdno)
    Called by slotChildOutput() this function copies data arriving from the child process' stdout to the respective buffer and emits the signal receivedStdout().
    StringclassName()
    voidclearArguments()
    Clear a command line argument list that has been set by using operator<<.
    voidcloseAll()
    booleanclosePty()
    Deletes the optional utmp entry and closes the pty.
    booleancloseStderr()
    Shuts down the Stderr communication link.
    booleancloseStdin()
    Shuts down the Stdin communication link.
    booleancloseStdout()
    Shuts down the Stdout communication link.
    protected voidcommClose()
    Cleans up the communication links to the child after it has exited.
    protected intcommSetupDoneC()
    Called right after a (successful) fork(), but before an exec() on the child process' side.
    protected intcommSetupDoneP()
    Called right after a (successful) fork() on the parent side.
    booleancoreDumped()
    Checks whether a killed process dumped core.
    voiddetach()
    Detaches KProcess from child process.
    voiddispose()
    Delete the wrapped C++ instance ahead of finalize()
    intexitSignal()
    Returns the signal the process was killed by.
    intexitStatus()
    Returns the exit status of the process.
    protected voidfinalize()
    Deletes the wrapped C++ instance
    booleanisDisposed()
    Has the wrapped C++ instance been deleted?
    booleanisRunning()
    Checks whether the process is running.
    booleankill(int signo)
    Stop the process (by sending it a signal).
    booleankill()
    QMetaObjectmetaObject()
    booleannormalExit()
    Checks whether the process exited cleanly.
    KProcessop_write(String arg)
    Sets the executable and the command line argument list for this process.
    KProcessop_write(String[] args)
    Sets the executable and the command line argument list for this process, in a single method call, or add a list of arguments.
    intpid()
    Returns the process id of the process.
    protected voidprocessHasExited(int state)
    Immediately called after a successfully started process in NotifyOnExit mode has exited.
    static Stringquote(String arg)
    This function can be used to quote an argument string such that the shell processes it properly.
    voidresume()
    Resume processing of data from stdout of the child process.
    booleanrunPrivileged()
    Returns whether the started process will drop any setuid/setgid privileges or whether it will keep them.
    protected voidsetBinaryExecutable(String filename)
    Specify the actual executable that should be started (first argument to execve) Normally the the first argument is the executable but you can override that with this function.
    voidsetEnvironment(String name, String value)
    Adds the variable name to the process' environment.
    booleansetPriority(int prio)
    Sets the scheduling priority of the process.
    voidsetRunPrivileged(boolean keepPrivileges)
    Controls whether the started process should drop any setuid/setgid privileges or whether it should keep them.
    protected intsetupCommunication(int comm)
    This function is called from start() right before a fork() takes place.
    protected voidsetupEnvironment()
    Sets up the environment according to the data passed via setEnvironment()
    voidsetUseShell(boolean useShell, String shell)
    Specify whether to start the command via a shell or directly.
    voidsetUseShell(boolean useShell)
    voidsetWorkingDirectory(String dir)
    Changes the current working directory (CWD) of the process to be started.
    booleansignalled()
    Checks whether the process was killed by a signal.
    protected voidslotChildError(int fdno)
    This slot gets activated when data from the child's stderr arrives.
    protected voidslotChildOutput(int fdno)
    This slot gets activated when data from the child's stdout arrives.
    protected voidslotSendData(int dummy)
    Called when another bulk of data can be sent to the child's stdin.
    booleanstart(int runmode, int comm)
    Starts the process.
    booleanstart(int runmode)
    booleanstart()
    voidsuspend()
    Suspend processing of data from stdout of the child process.
    booleanwaitThread(int timeout)
    Suspend execution of the current thread until the child process dies or the timeout hits.
    booleanwaitThread()
    booleanwriteStdin(String buffer, int buflen)
    Transmit data to the child process' stdin.

    Field Detail

    All

    public static final int All

    AllOutput

    public static final int AllOutput

    Block

    public static final int Block

    DontCare

    public static final int DontCare
    Run-modes for a child process.

    UNKNOWN: Run-modes for a child process.

    NoCommunication

    public static final int NoCommunication
    Modes in which the communication channel can be opened. If communication for more than one channel is required, the values have to be or'ed together, for example to get communication with stdout as well as with stdin, you would specify Stdin | Stdout If NoRead is specified in conjunction with Stdout, no data is actually read from Stdout but only the signal receivedStdout(int fd, int &len) is emitted.

    UNKNOWN: Modes in which the communication channel can be opened.

    NoRead

    public static final int NoRead

    NotifyOnExit

    public static final int NotifyOnExit

    OwnGroup

    public static final int OwnGroup

    PrioHigh

    public static final int PrioHigh

    PrioHigher

    public static final int PrioHigher

    PrioHighest

    public static final int PrioHighest

    PrioLow

    public static final int PrioLow

    PrioLower

    public static final int PrioLower

    PrioLowest

    public static final int PrioLowest
    More or less intuitive constants for use with setPriority().

    UNKNOWN: More or less intuitive constants for use with setPriority().

    PrioNormal

    public static final int PrioNormal

    Stderr

    public static final int Stderr

    Stdin

    public static final int Stdin

    Stdout

    public static final int Stdout

    Constructor Detail

    KProcess

    protected KProcess(Class dummy)

    KProcess

    public KProcess(QObject parent, String name)
    Constructor

    UNKNOWN: Constructor

    KProcess

    public KProcess(QObject parent)

    KProcess

    public KProcess()
    Constructor

    UNKNOWN: Constructor

    Method Detail

    childError

    protected int childError(int fdno)
    Called by slotChildError() this function copies data arriving from the child process' stderr to the respective buffer and emits the signal receivedStderr().

    UNKNOWN: Called by slotChildError() this function copies data arriving from the child process' stderr to the respective buffer and emits the signal receivedStderr().

    childOutput

    protected int childOutput(int fdno)
    Called by slotChildOutput() this function copies data arriving from the child process' stdout to the respective buffer and emits the signal receivedStdout().

    UNKNOWN: Called by slotChildOutput() this function copies data arriving from the child process' stdout to the respective buffer and emits the signal receivedStdout().

    className

    public String className()

    clearArguments

    public void clearArguments()
    Clear a command line argument list that has been set by using operator<<.

    UNKNOWN: Clear a command line argument list that has been set by using operator<<.

    closeAll

    public void closeAll()

    See Also: KProcess @see KProcess @see KProcess @see KProcess

    UNKNOWN: Close stdin, stdout, stderr and the pty This is the same that calling all close functions in a row: @brief Close stdin, stdout, stderr and the pty

    closePty

    public boolean closePty()
    Deletes the optional utmp entry and closes the pty. Make sure to shut down any communication links that are using the pty before calling this function.

    Returns: false if the pty is not open (any more).

    UNKNOWN: Deletes the optional utmp entry and closes the pty.

    closeStderr

    public boolean closeStderr()
    Shuts down the Stderr communication link. If no pty is used, any further attempts by the child to write to its stderr file descriptor will cause it to receive a SIGPIPE.

    Returns: false if no Stderr communication link exists (any more).

    UNKNOWN: Shuts down the Stderr communication link.

    closeStdin

    public boolean closeStdin()
    Shuts down the Stdin communication link. If no pty is used, this causes "EOF" to be indicated on the child's stdin file descriptor.

    Returns: false if no Stdin communication link exists (any more).

    UNKNOWN: Shuts down the Stdin communication link.

    closeStdout

    public boolean closeStdout()
    Shuts down the Stdout communication link. If no pty is used, any further attempts by the child to write to its stdout file descriptor will cause it to receive a SIGPIPE.

    Returns: false if no Stdout communication link exists (any more).

    UNKNOWN: Shuts down the Stdout communication link.

    commClose

    protected void commClose()
    Cleans up the communication links to the child after it has exited. This function should act upon the values of pid() and runs. See the kprocess.cpp source for details.
  • If pid() returns zero, the communication links should be closed only.
  • if pid() returns non-zero and runs is false, all data immediately available from the communication links should be processed before closing them.
  • if pid() returns non-zero and runs is true, the communication links should be monitored for data until the file handle returned by KProcessController.theKProcessController.notifierFd() becomes ready for reading - when it triggers, runs should be reset to false, and the function should be immediately left without closing anything.
  • The previous semantics of this function are forward-compatible, but should be avoided, as they are prone to race conditions and can cause KProcess (and thus the whole program) to lock up under certain circumstances. At the end the function closes the communication links in any case. Additionally
  • if runs is true, the communication links are monitored for data until all of them have returned EOF. Note that if any system function is interrupted (errno == EINTR) the polling loop should be aborted.
  • if runs is false, all data immediately available from the communication links is processed.
  • @short Cleans up the communication links to the child after it has exited.

    commSetupDoneC

    protected int commSetupDoneC()
    Called right after a (successful) fork(), but before an exec() on the child process' side. It usually duplicates the in[0], out[1] and err[1] file handles to the respective standard I/O handles.

    UNKNOWN: Called right after a (successful) fork(), but before an exec() on the child process' side.

    commSetupDoneP

    protected int commSetupDoneP()
    Called right after a (successful) fork() on the parent side. This function will usually do some communications cleanup, like closing in[0], out[1] and out[1]. Furthermore, it must also create the QSocketNotifiers innot, outnot and errnot and connect their Qt signals to the respective KProcess slots. For a more detailed explanation, it is best to have a look at the default implementation in kprocess.cpp.

    UNKNOWN: Called right after a (successful) fork() on the parent side.

    coreDumped

    public boolean coreDumped()
    Checks whether a killed process dumped core.

    Returns: true if signalled() returns true and the process dumped core. Note that on systems that don't define the WCOREDUMP macro, the return value is always false.

    UNKNOWN: Checks whether a killed process dumped core.

    detach

    public void detach()
    Detaches KProcess from child process. All communication is closed. No exit notification is emitted any more for the child process. Deleting the KProcess will no longer kill the child process. Note that the current process remains the parent process of the child process.

    UNKNOWN: Detaches KProcess from child process.

    dispose

    public void dispose()
    Delete the wrapped C++ instance ahead of finalize()

    exitSignal

    public int exitSignal()
    Returns the signal the process was killed by.

    Returns: the signal number that caused the process to exit. Note that this value is not valid if signalled() returns false.

    UNKNOWN: Returns the signal the process was killed by.

    exitStatus

    public int exitStatus()
    Returns the exit status of the process.

    Returns: the exit status of the process. Note that this value is not valid if normalExit() returns false.

    UNKNOWN: Returns the exit status of the process.

    finalize

    protected void finalize()
    Deletes the wrapped C++ instance

    isDisposed

    public boolean isDisposed()
    Has the wrapped C++ instance been deleted?

    isRunning

    public boolean isRunning()
    Checks whether the process is running.

    Returns: true if the process is (still) considered to be running

    UNKNOWN: Checks whether the process is running.

    kill

    public boolean kill(int signo)
    Stop the process (by sending it a signal).

    Parameters: signo The signal to send. The default is SIGTERM.

    Returns: true if the signal was delivered successfully.

    UNKNOWN: Stop the process (by sending it a signal).

    kill

    public boolean kill()

    metaObject

    public QMetaObject metaObject()

    normalExit

    public boolean normalExit()
    Checks whether the process exited cleanly.

    Returns: true if the process has already finished and has exited "voluntarily", ie: it has not been killed by a signal.

    UNKNOWN: Checks whether the process exited cleanly.

    op_write

    public KProcess op_write(String arg)
    Sets the executable and the command line argument list for this process. For example, doing an "ls -l /usr/local/bin" can be achieved by:
    		  KProcess p;
    		  ...
    		  p << "ls" << "-l" << "/usr/local/bin"
    		  

    Parameters: arg the argument to add

    Returns: a reference to this KProcess

    UNKNOWN: Sets the executable and the command line argument list for this process.

    op_write

    public KProcess op_write(String[] args)
    Sets the executable and the command line argument list for this process, in a single method call, or add a list of arguments.

    Parameters: args the arguments to add

    Returns: a reference to this KProcess

    UNKNOWN: Sets the executable and the command line argument list for this process, in a single method call, or add a list of arguments.

    pid

    public int pid()
    Returns the process id of the process. If it is called after the process has exited, it returns the process id of the last child process that was created by this instance of KProcess. Calling it before any child process has been started by this KProcess instance causes pid() to return 0.

    Returns: the pid of the process or 0 if no process has been started yet.

    UNKNOWN: Returns the process id of the process.

    processHasExited

    protected void processHasExited(int state)
    Immediately called after a successfully started process in NotifyOnExit mode has exited. This function normally calls commClose() and emits the processExited() signal.

    Parameters: state the exit code of the process as returned by waitpid()

    UNKNOWN: Immediately called after a successfully started process in NotifyOnExit mode has exited.

    quote

    public static String quote(String arg)
    This function can be used to quote an argument string such that the shell processes it properly. This is e. g. necessary for user-provided file names which may contain spaces or quotes. It also prevents expansion of wild cards and environment variables.

    Parameters: arg the argument to quote

    Returns: the quoted argument

    UNKNOWN: This function can be used to quote an argument string such that the shell processes it properly.

    resume

    public void resume()
    Resume processing of data from stdout of the child process.

    UNKNOWN: Resume processing of data from stdout of the child process.

    runPrivileged

    public boolean runPrivileged()
    Returns whether the started process will drop any setuid/setgid privileges or whether it will keep them.

    Returns: true if the process runs privileged

    UNKNOWN: Returns whether the started process will drop any setuid/setgid privileges or whether it will keep them.

    setBinaryExecutable

    protected void setBinaryExecutable(String filename)
    Specify the actual executable that should be started (first argument to execve) Normally the the first argument is the executable but you can override that with this function.

    UNKNOWN: Specify the actual executable that should be started (first argument to execve) Normally the the first argument is the executable but you can override that with this function.

    setEnvironment

    public void setEnvironment(String name, String value)
    Adds the variable name to the process' environment. This function must be called before starting the process.

    Parameters: name the name of the environment variable value the new value for the environment variable

    UNKNOWN: Adds the variable name to the process' environment.

    setPriority

    public boolean setPriority(int prio)
    Sets the scheduling priority of the process.

    Parameters: prio the new priority in the range -20 (high) to 19 (low).

    Returns: false on error; see setpriority(2) for possible reasons.

    UNKNOWN: Sets the scheduling priority of the process.

    setRunPrivileged

    public void setRunPrivileged(boolean keepPrivileges)
    Controls whether the started process should drop any setuid/setgid privileges or whether it should keep them. Note that this function is mostly a dummy, as the KDE libraries currently refuse to run with setuid/setgid privileges. The default is false: drop privileges

    Parameters: keepPrivileges true to keep the privileges

    UNKNOWN: Controls whether the started process should drop any setuid/setgid privileges or whether it should keep them.

    setupCommunication

    protected int setupCommunication(int comm)
    This function is called from start() right before a fork() takes place. According to the comm parameter this function has to initialize the in, out and err data members of KProcess. This function should return 1 if setting the needed communication channels was successful. The default implementation is to create UNIX STREAM sockets for the communication, but you could reimplement this function to establish a TCP/IP communication for network communication, for example.

    UNKNOWN: This function is called from start() right before a fork() takes place.

    setupEnvironment

    protected void setupEnvironment()
    Sets up the environment according to the data passed via setEnvironment()

    UNKNOWN: Sets up the environment according to the data passed via setEnvironment()

    setUseShell

    public void setUseShell(boolean useShell, String shell)
    Specify whether to start the command via a shell or directly. The default is to start the command directly. If useShell is true shell will be used as shell, or if shell is empty, /bin/sh will be used. When using a shell, the caller should make sure that all filenames etc. are properly quoted when passed as argument.

    Parameters: useShell true if the command should be started via a shell shell the path to the shell that will execute the process, or 0 to use /bin/sh. Use getenv("SHELL") to use the user's default shell, but note that doing so is usually a bad idea for shell compatibility reasons.

    See Also: KProcess

    UNKNOWN: Specify whether to start the command via a shell or directly.

    setUseShell

    public void setUseShell(boolean useShell)

    setWorkingDirectory

    public void setWorkingDirectory(String dir)
    Changes the current working directory (CWD) of the process to be started. This function must be called before starting the process.

    Parameters: dir the new directory

    UNKNOWN: Changes the current working directory (CWD) of the process to be started.

    signalled

    public boolean signalled()
    Checks whether the process was killed by a signal.

    Returns: true if the process has already finished and has not exited "voluntarily", ie: it has been killed by a signal.

    UNKNOWN: Checks whether the process was killed by a signal.

    slotChildError

    protected void slotChildError(int fdno)
    This slot gets activated when data from the child's stderr arrives. It usually calls childError().

    Parameters: fdno the file descriptor for the output

    UNKNOWN: This slot gets activated when data from the child's stderr arrives.

    slotChildOutput

    protected void slotChildOutput(int fdno)
    This slot gets activated when data from the child's stdout arrives. It usually calls childOutput().

    Parameters: fdno the file descriptor for the output

    UNKNOWN: This slot gets activated when data from the child's stdout arrives.

    slotSendData

    protected void slotSendData(int dummy)
    Called when another bulk of data can be sent to the child's stdin. If there is no more data to be sent to stdin currently available, this function must disable the QSocketNotifier innot.

    Parameters: dummy ignore this argument

    UNKNOWN: Called when another bulk of data can be sent to the child's stdin.

    start

    public boolean start(int runmode, int comm)
    Starts the process. For a detailed description of the various run modes and communication semantics, have a look at the general description of the KProcess class. Note that if you use setUsePty( Stdout | Stderr, \ ), you cannot use Stdout | Stderr here - instead, use Stdout only to receive the mixed output. The following problems could cause this function to return false:
  • The process is already running.
  • The command line argument list is empty.
  • The the comm parameter is incompatible with the selected pty usage.
  • The starting of the process failed (could not fork).
  • The executable was not found.
  • Parameters: runmode The Run-mode for the process. comm Specifies which communication links should be established to the child process (stdin/stdout/stderr). By default, no communication takes place and the respective communication signals will never get emitted.

    Returns: true on success, false on error (see above for error conditions)

    UNKNOWN: Starts the process.

    start

    public boolean start(int runmode)

    start

    public boolean start()

    suspend

    public void suspend()
    Suspend processing of data from stdout of the child process.

    UNKNOWN: Suspend processing of data from stdout of the child process.

    waitThread

    public boolean waitThread(int timeout)
    Suspend execution of the current thread until the child process dies or the timeout hits. This function is not recommended for programs with a GUI.

    Parameters: timeout timeout in seconds. -1 means wait indefinitely.

    Returns: true if the process exited, false if the timeout hit.

    UNKNOWN: Suspend execution of the current thread until the child process dies or the timeout hits.

    waitThread

    public boolean waitThread()

    writeStdin

    public boolean writeStdin(String buffer, int buflen)
    Transmit data to the child process' stdin. This function may return false in the following cases:
  • The process is not currently running. This implies that you cannot use this function in Block mode.
  • Communication to stdin has not been requested in the start() call.
  • Transmission of data to the child process by a previous call to writeStdin() is still in progress.
  • Please note that the data is sent to the client asynchronously, so when this function returns, the data might not have been processed by the child process. That means that you must not free buffer or call writeStdin() again until either a wroteStdin() signal indicates that the data has been sent or a processExited() signal shows that the child process is no longer alive. If all the data has been sent to the client, the signal wroteStdin() will be emitted.

    Parameters: buffer the buffer to write buflen the length of the buffer

    Returns: false if an error has occurred

    UNKNOWN: Transmit data to the child process' stdin.