Class Subprocess
GSubprocess allows the creation of and interaction with child
processes.
Processes can be communicated with using standard GIO-style APIs (ie:
InputStream, OutputStream). There are GIO-style APIs
to wait for process termination (ie: cancellable and with an asynchronous
variant).
There is an API to force a process to terminate, as well as a race-free API for sending UNIX signals to a subprocess.
One major advantage that GIO brings over the core GLib library is
comprehensive API for asynchronous I/O, such
OutputStream.spliceAsync(org.gnome.gio.InputStream, java.util.Set<org.gnome.gio.OutputStreamSpliceFlags>, int, org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback). This makes GSubprocess
significantly more powerful and flexible than equivalent APIs in
some other languages such as the subprocess.py
included with Python. For example, using GSubprocess one could
create two child processes, reading standard output from the first,
processing it, and writing to the input stream of the second, all
without blocking the main loop.
A powerful communicate(byte[], org.gnome.gio.Cancellable, org.javagi.base.Out<byte[]>, org.javagi.base.Out<byte[]>) API is provided similar to the
communicate() method of subprocess.py. This enables very easy
interaction with a subprocess that has been opened with pipes.
GSubprocess defaults to tight control over the file descriptors open
in the child process, avoiding dangling-FD issues that are caused by
a simple fork()/exec(). The only open file descriptors in the
spawned process are ones that were explicitly specified by the
GSubprocess API (unless G_SUBPROCESS_FLAGS_INHERIT_FDS was
specified).
GSubprocess will quickly reap all child processes as they exit,
avoiding ‘zombie processes’ remaining around for long periods of
time. wait_(org.gnome.gio.Cancellable) can be used to wait for this to happen,
but it will happen even without the call being explicitly made.
As a matter of principle, GSubprocess has no API that accepts
shell-style space-separated strings. It will, however, match the
typical shell behaviour of searching the PATH for executables that do
not contain a directory separator in their name. By default, the PATH
of the current process is used. You can specify
G_SUBPROCESS_FLAGS_SEARCH_PATH_FROM_ENVP to use the PATH of the
launcher environment instead.
GSubprocess attempts to have a very simple API for most uses (ie:
spawning a subprocess with arguments and support for most typical
kinds of input and output redirection). See Subprocess(). The
SubprocessLauncher API is provided for more complicated cases
(advanced types of redirection, environment variable manipulation,
change of working directory, child setup functions, etc).
A typical use of GSubprocess will involve calling
Subprocess(), followed by waitAsync(org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback) or
wait_(org.gnome.gio.Cancellable). After the process exits, the status can be
checked using functions such as getIfExited() (which
are similar to the familiar WIFEXITED-style POSIX macros).
Note that as of GLib 2.82, creating a GSubprocess causes the signal
SIGPIPE to be ignored for the remainder of the program. If you are writing
a command-line utility that uses GSubprocess, you may need to take into
account the fact that your program will not automatically be killed
if it tries to write to stdout after it has been closed.
- Since:
- 2.40
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSubprocess.Builder<B extends Subprocess.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.Nested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gio.Initable
Initable.Initable$Impl, Initable.InitableIface -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new Subprocess.Subprocess(@Nullable String @Nullable [] argv, Set<SubprocessFlags> flags) Create a new process with the given flags and argument list.Subprocess(@Nullable String @Nullable [] argv, SubprocessFlags... flags) Create a new process with the given flags and argument list.Subprocess(MemorySegment address) Create a Subprocess proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionprotected SubprocessasParent()Returns this instance as if it were its parent type.static Subprocess.Builder<? extends Subprocess.Builder> builder()ASubprocess.Builderobject constructs aSubprocesswith the specified properties.booleancommunicate(byte @Nullable [] stdinBuf, @Nullable Cancellable cancellable, @Nullable Out<byte[]> stdoutBuf, @Nullable Out<byte[]> stderrBuf) Communicate with the subprocess until it terminates, and all input and output has been completed.voidcommunicateAsync(byte @Nullable [] stdinBuf, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Asynchronous version of g_subprocess_communicate().booleancommunicateFinish(AsyncResult result, @Nullable Out<byte[]> stdoutBuf, @Nullable Out<byte[]> stderrBuf) Complete an invocation of g_subprocess_communicate_async().booleancommunicateUtf8(@Nullable String stdinBuf, @Nullable Cancellable cancellable, @Nullable Out<String> stdoutBuf, @Nullable Out<String> stderrBuf) Like g_subprocess_communicate(), but validates the output of the process as UTF-8, and returns it as a regular NUL terminated string.voidcommunicateUtf8Async(@Nullable String stdinBuf, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Asynchronous version of g_subprocess_communicate_utf8().booleancommunicateUtf8Finish(AsyncResult result, @Nullable Out<String> stdoutBuf, @Nullable Out<String> stderrBuf) Complete an invocation of g_subprocess_communicate_utf8_async().voidUse an operating-system specific method to attempt an immediate, forceful termination of the process.intCheck the exit status of the subprocess, given that it exited normally.@Nullable StringOn UNIX, returns the process ID as a decimal string.booleanCheck if the given subprocess exited normally (ie: by way of exit() or return from main()).booleanCheck if the given subprocess terminated in response to a signal.intGets the raw status code of the process, as from waitpid().@Nullable InputStreamGets theGInputStreamfrom which to read the stderr output ofsubprocess.@Nullable OutputStreamGets theGOutputStreamthat you can write to in order to give data to the stdin ofsubprocess.@Nullable InputStreamGets theGInputStreamfrom which to read the stdout output ofsubprocess.booleanChecks if the process was "successful".intGet the signal number that caused the subprocess to terminate, given that it terminated due to a signal.static @Nullable TypegetType()Get the GType of the Subprocess classvoidsendSignal(int signalNum) Sends the UNIX signalsignalNumto the subprocess, if it is still running.booleanwait_(@Nullable Cancellable cancellable) Synchronously wait for the subprocess to terminate.voidwaitAsync(@Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Wait for the subprocess to terminate.booleanwaitCheck(@Nullable Cancellable cancellable) Combines g_subprocess_wait() with g_spawn_check_wait_status().voidwaitCheckAsync(@Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Combines g_subprocess_wait_async() with g_spawn_check_wait_status().booleanwaitCheckFinish(AsyncResult result) Collects the result of a previous call to g_subprocess_wait_check_async().booleanwaitFinish(AsyncResult result) Collects the result of a previous call to g_subprocess_wait_async().Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getMemoryLayout, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
Subprocess
Create a Subprocess proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Subprocess
public Subprocess(@Nullable String @Nullable [] argv, Set<SubprocessFlags> flags) throws GErrorException Create a new process with the given flags and argument list.The argument list is expected to be
null-terminated.- Parameters:
argv- commandline arguments for the subprocessflags- flags that define the behaviour of the subprocess- Throws:
GErrorException- seeGError- Since:
- 2.40
-
Subprocess
public Subprocess(@Nullable String @Nullable [] argv, SubprocessFlags... flags) throws GErrorException Create a new process with the given flags and argument list.The argument list is expected to be
null-terminated.- Parameters:
argv- commandline arguments for the subprocessflags- flags that define the behaviour of the subprocess- Throws:
GErrorException- seeGError- Since:
- 2.40
-
Subprocess
public Subprocess()Creates a new Subprocess.
-
-
Method Details
-
getType
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
communicate
public boolean communicate(byte @Nullable [] stdinBuf, @Nullable Cancellable cancellable, @Nullable Out<byte[]> stdoutBuf, @Nullable Out<byte[]> stderrBuf) throws GErrorException Communicate with the subprocess until it terminates, and all input and output has been completed.If
stdinBufis given, the subprocess must have been created withSubprocessFlags.STDIN_PIPE. The given data is fed to the stdin of the subprocess and the pipe is closed (ie: EOF).At the same time (as not to cause blocking when dealing with large amounts of data), if
SubprocessFlags.STDOUT_PIPEorSubprocessFlags.STDERR_PIPEwere used, reads from those streams. The data that was read is returned instdoutand/or thestderr.If the subprocess was created with
SubprocessFlags.STDOUT_PIPE,stdoutBufwill contain the data read from stdout. Otherwise, for subprocesses not created withSubprocessFlags.STDOUT_PIPE,stdoutBufwill be set tonull. Similar provisions apply tostderrBufandSubprocessFlags.STDERR_PIPE.As usual, any output variable may be given as
nullto ignore it.If you desire the stdout and stderr data to be interleaved, create the subprocess with
SubprocessFlags.STDOUT_PIPEandSubprocessFlags.STDERR_MERGE. The merged result will be returned instdoutBufandstderrBufwill be set tonull.In case of any error (including cancellation),
falsewill be returned witherrorset. Some or all of the stdin data may have been written. Any stdout or stderr data that has been read will be discarded. None of the out variables (aside fromerror)will have been set to anything in particular and should not be inspected.In the case that
trueis returned, the subprocess has exited and the exit status inspection APIs (eg: g_subprocess_get_if_exited(), g_subprocess_get_exit_status()) may be used.You should not attempt to use any of the subprocess pipes after starting this function, since they may be left in strange states, even if the operation was cancelled. You should especially not attempt to interact with the pipes while the operation is in progress (either from another thread or if using the asynchronous version).
- Parameters:
stdinBuf- data to send to the stdin of the subprocess, ornullcancellable- aGCancellablestdoutBuf- data read from the subprocess stdoutstderrBuf- data read from the subprocess stderr- Returns:
trueif successful- Throws:
GErrorException- seeGError- Since:
- 2.40
-
communicateAsync
public void communicateAsync(byte @Nullable [] stdinBuf, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Asynchronous version of g_subprocess_communicate(). Complete invocation with g_subprocess_communicate_finish().- Parameters:
stdinBuf- Input data, ornullcancellable- Cancellablecallback- Callback
-
communicateFinish
public boolean communicateFinish(AsyncResult result, @Nullable Out<byte[]> stdoutBuf, @Nullable Out<byte[]> stderrBuf) throws GErrorException Complete an invocation of g_subprocess_communicate_async().- Parameters:
result- ResultstdoutBuf- Return location for stdout datastderrBuf- Return location for stderr data- Throws:
GErrorException- seeGError
-
communicateUtf8
public boolean communicateUtf8(@Nullable String stdinBuf, @Nullable Cancellable cancellable, @Nullable Out<String> stdoutBuf, @Nullable Out<String> stderrBuf) throws GErrorException Like g_subprocess_communicate(), but validates the output of the process as UTF-8, and returns it as a regular NUL terminated string.On error,
stdoutBufandstderrBufwill be set to undefined values and should not be used.- Parameters:
stdinBuf- data to send to the stdin of the subprocess, ornullcancellable- aGCancellablestdoutBuf- data read from the subprocess stdoutstderrBuf- data read from the subprocess stderr- Throws:
GErrorException- seeGError
-
communicateUtf8Async
public void communicateUtf8Async(@Nullable String stdinBuf, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Asynchronous version of g_subprocess_communicate_utf8(). Complete invocation with g_subprocess_communicate_utf8_finish().- Parameters:
stdinBuf- Input data, ornullcancellable- Cancellablecallback- Callback
-
communicateUtf8Finish
public boolean communicateUtf8Finish(AsyncResult result, @Nullable Out<String> stdoutBuf, @Nullable Out<String> stderrBuf) throws GErrorException Complete an invocation of g_subprocess_communicate_utf8_async().- Parameters:
result- ResultstdoutBuf- Return location for stdout datastderrBuf- Return location for stderr data- Throws:
GErrorException- seeGError
-
forceExit
public void forceExit()Use an operating-system specific method to attempt an immediate, forceful termination of the process. There is no mechanism to determine whether or not the request itself was successful; however, you can use g_subprocess_wait() to monitor the status of the process after calling this function.On Unix, this function sends
SIGKILL.- Since:
- 2.40
-
getExitStatus
public int getExitStatus()Check the exit status of the subprocess, given that it exited normally. This is the value passed to the exit() system call or the return value from main.This is equivalent to the system WEXITSTATUS macro.
It is an error to call this function before g_subprocess_wait() and unless g_subprocess_get_if_exited() returned
true.- Returns:
- the exit status
- Since:
- 2.40
-
getIdentifier
On UNIX, returns the process ID as a decimal string. On Windows, returns the result of GetProcessId() also as a string. If the subprocess has terminated, this will returnnull.- Returns:
- the subprocess identifier, or
nullif the subprocess has terminated - Since:
- 2.40
-
getIfExited
public boolean getIfExited()Check if the given subprocess exited normally (ie: by way of exit() or return from main()).This is equivalent to the system WIFEXITED macro.
It is an error to call this function before g_subprocess_wait() has returned.
- Returns:
trueif the case of a normal exit- Since:
- 2.40
-
getIfSignaled
public boolean getIfSignaled()Check if the given subprocess terminated in response to a signal.This is equivalent to the system WIFSIGNALED macro.
It is an error to call this function before g_subprocess_wait() has returned.
- Returns:
trueif the case of termination due to a signal- Since:
- 2.40
-
getStatus
public int getStatus()Gets the raw status code of the process, as from waitpid().This value has no particular meaning, but it can be used with the macros defined by the system headers such as WIFEXITED. It can also be used with g_spawn_check_wait_status().
It is more likely that you want to use g_subprocess_get_if_exited() followed by g_subprocess_get_exit_status().
It is an error to call this function before g_subprocess_wait() has returned.
- Returns:
- the (meaningless) waitpid() exit status from the kernel
- Since:
- 2.40
-
getStderrPipe
Gets theGInputStreamfrom which to read the stderr output ofsubprocess.The process must have been created with
SubprocessFlags.STDERR_PIPE, otherwisenullwill be returned.- Returns:
- the stderr pipe
- Since:
- 2.40
-
getStdinPipe
Gets theGOutputStreamthat you can write to in order to give data to the stdin ofsubprocess.The process must have been created with
SubprocessFlags.STDIN_PIPEand notSubprocessFlags.STDIN_INHERIT, otherwisenullwill be returned.- Returns:
- the stdout pipe
- Since:
- 2.40
-
getStdoutPipe
Gets theGInputStreamfrom which to read the stdout output ofsubprocess.The process must have been created with
SubprocessFlags.STDOUT_PIPE, otherwisenullwill be returned.- Returns:
- the stdout pipe
- Since:
- 2.40
-
getSuccessful
public boolean getSuccessful()Checks if the process was "successful". A process is considered successful if it exited cleanly with an exit status of 0, either by way of the exit() system call or return from main().It is an error to call this function before g_subprocess_wait() has returned.
- Returns:
trueif the process exited cleanly with a exit status of 0- Since:
- 2.40
-
getTermSig
public int getTermSig()Get the signal number that caused the subprocess to terminate, given that it terminated due to a signal.This is equivalent to the system WTERMSIG macro.
It is an error to call this function before g_subprocess_wait() and unless g_subprocess_get_if_signaled() returned
true.- Returns:
- the signal causing termination
- Since:
- 2.40
-
sendSignal
public void sendSignal(int signalNum) Sends the UNIX signalsignalNumto the subprocess, if it is still running.This API is race-free. If the subprocess has terminated, it will not be signalled.
This API is not available on Windows.
- Parameters:
signalNum- the signal number to send- Since:
- 2.40
-
wait_
Synchronously wait for the subprocess to terminate.After the process terminates you can query its exit status with functions such as g_subprocess_get_if_exited() and g_subprocess_get_exit_status().
This function does not fail in the case of the subprocess having abnormal termination. See g_subprocess_wait_check() for that.
Cancelling
cancellabledoesn't kill the subprocess. Call g_subprocess_force_exit() if it is desirable.- Parameters:
cancellable- aGCancellable- Returns:
trueon success,falseifcancellablewas cancelled- Throws:
GErrorException- seeGError- Since:
- 2.40
-
waitAsync
Wait for the subprocess to terminate.This is the asynchronous version of g_subprocess_wait().
- Parameters:
cancellable- aGCancellable, ornullcallback- aGAsyncReadyCallbackto call when the operation is complete- Since:
- 2.40
-
waitCheck
Combines g_subprocess_wait() with g_spawn_check_wait_status().- Parameters:
cancellable- aGCancellable- Returns:
trueon success,falseif process exited abnormally, orcancellablewas cancelled- Throws:
GErrorException- seeGError- Since:
- 2.40
-
waitCheckAsync
public void waitCheckAsync(@Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) Combines g_subprocess_wait_async() with g_spawn_check_wait_status().This is the asynchronous version of g_subprocess_wait_check().
- Parameters:
cancellable- aGCancellable, ornullcallback- aGAsyncReadyCallbackto call when the operation is complete- Since:
- 2.40
-
waitCheckFinish
Collects the result of a previous call to g_subprocess_wait_check_async().- Parameters:
result- theGAsyncResultpassed to yourGAsyncReadyCallback- Returns:
trueif successful, orfalsewitherrorset- Throws:
GErrorException- seeGError- Since:
- 2.40
-
waitFinish
Collects the result of a previous call to g_subprocess_wait_async().- Parameters:
result- theGAsyncResultpassed to yourGAsyncReadyCallback- Returns:
trueif successful, orfalsewitherrorset- Throws:
GErrorException- seeGError- Since:
- 2.40
-
builder
ASubprocess.Builderobject constructs aSubprocesswith the specified properties. Use the variousset...()methods to set properties, and finish construction withSubprocess.Builder.build().- Returns:
- the builder object
-