class Gio::Subprocess

Overview

#GSubprocess allows the creation of and interaction with child processes.

Processes can be communicated with using standard GIO-style APIs (ie: #GInputStream, #GOutputStream). 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 g_output_stream_splice_async(). 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 g_subprocess_communicate() 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. g_subprocess_wait() 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 g_subprocess_new(). The #GSubprocessLauncher 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 g_subprocess_new(), followed by g_subprocess_wait_async() or g_subprocess_wait(). After the process exits, the status can be checked using functions such as g_subprocess_get_if_exited() (which are similar to the familiar WIFEXITED-style POSIX macros).

Included Modules

Defined in:

lib/gi-crystal/src/auto/gio-2.0/subprocess.cr

Constructors

Class Method Summary

Instance Method Summary

Instance methods inherited from module Gio::Initable

init(cancellable : Gio::Cancellable | Nil) : Bool init, newv(object_type : UInt64, parameters : Enumerable(GObject::Parameter), cancellable : Gio::Cancellable | Nil) : GObject::Object newv, to_unsafe to_unsafe

Constructor methods inherited from module Gio::Initable

cast(obj : GObject::Object) : self cast

Class methods inherited from module Gio::Initable

cast?(obj : GObject::Object) : self | Nil cast?, g_type : UInt64 g_type

Instance methods inherited from class GObject::Object

==(other : self) ==, bind_property(source_property : String, target : GObject::Object, target_property : String, flags : GObject::BindingFlags) : GObject::Binding bind_property, bind_property_full(source_property : String, target : GObject::Object, target_property : String, flags : GObject::BindingFlags, transform_to : GObject::Closure, transform_from : GObject::Closure) : GObject::Binding bind_property_full, data(key : String) : Pointer(Void) | Nil data, finalize finalize, freeze_notify : Nil freeze_notify, getv(names : Enumerable(String), values : Enumerable(_)) : Nil getv, hash(hasher) hash, notify(property_name : String) : Nil notify, notify_by_pspec(pspec : GObject::ParamSpec) : Nil notify_by_pspec, notify_signal notify_signal, property(property_name : String, value : _) : Nil property, qdata(quark : UInt32) : Pointer(Void) | Nil qdata, ref_count : UInt32 ref_count, run_dispose : Nil run_dispose, set_data(key : String, data : Pointer(Void) | Nil) : Nil set_data, set_property(property_name : String, value : _) : Nil set_property, steal_data(key : String) : Pointer(Void) | Nil steal_data, steal_qdata(quark : UInt32) : Pointer(Void) | Nil steal_qdata, thaw_notify : Nil thaw_notify, to_unsafe : Pointer(Void) to_unsafe, watch_closure(closure : GObject::Closure) : Nil watch_closure

Constructor methods inherited from class GObject::Object

cast(obj : GObject::Object) : self cast, new(pointer : Pointer(Void), transfer : GICrystal::Transfer)
new
new
, newv(object_type : UInt64, parameters : Enumerable(GObject::Parameter)) : self newv

Class methods inherited from class GObject::Object

cast?(obj : GObject::Object) : self | Nil cast?, compat_control(what : UInt64, data : Pointer(Void) | Nil) : UInt64 compat_control, g_type : UInt64 g_type, interface_find_property(g_iface : GObject::TypeInterface, property_name : String) : GObject::ParamSpec interface_find_property, interface_list_properties(g_iface : GObject::TypeInterface) : Enumerable(GObject::ParamSpec) interface_list_properties

Macros inherited from class GObject::Object

previous_vfunc(*args) previous_vfunc, previous_vfunc!(*args) previous_vfunc!, signal(signature) signal

Constructor Detail

def self.new(argv : Enumerable(String), flags : Gio::SubprocessFlags) : self #

Create a new process with the given flags and varargs argument list. By default, matching the g_spawn_async() defaults, the child's stdin will be set to the system null device, and stdout/stderr will be inherited from the parent. You can use flags to control this behavior.

The argument list must be terminated with nil.


[View source]
def self.new #

Initialize a new Subprocess.


[View source]
def self.new(*, argv : Enumerable(String) | Nil = nil, flags : Gio::SubprocessFlags | Nil = nil) #

[View source]

Class Method Detail

def self.g_type : UInt64 #

Returns the type id (GType) registered in GLib type system.


[View source]

Instance Method Detail

def ==(other : self) #
Description copied from class Reference

Returns true if this reference is the same as other. Invokes same?.


def argv=(value : Enumerable(String)) : Enumerable(String) #

[View source]
def communicate(stdin_buf : GLib::Bytes | Nil, cancellable : Gio::Cancellable | Nil) : Bool #

Communicate with the subprocess until it terminates, and all input and output has been completed.

If stdin_buf is given, the subprocess must have been created with %G_SUBPROCESS_FLAGS_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 %G_SUBPROCESS_FLAGS_STDOUT_PIPE or %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those streams. The data that was read is returned in stdout and/or the stderr.

If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE, stdout_buf will contain the data read from stdout. Otherwise, for subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE, stdout_buf will be set to nil. Similar provisions apply to stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.

As usual, any output variable may be given as nil to ignore it.

If you desire the stdout and stderr data to be interleaved, create the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and %G_SUBPROCESS_FLAGS_STDERR_MERGE. The merged result will be returned in stdout_buf and stderr_buf will be set to nil.

In case of any error (including cancellation), false will be returned with error set. 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 from error) will have been set to anything in particular and should not be inspected.

In the case that true is 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).


[View source]
def communicate_async(stdin_buf : GLib::Bytes | Nil, cancellable : Gio::Cancellable | Nil, &callback : Gio::AsyncReadyCallback) : Nil #

Asynchronous version of g_subprocess_communicate(). Complete invocation with g_subprocess_communicate_finish().


[View source]
def communicate_finish(result : Gio::AsyncResult) : Bool #

Complete an invocation of g_subprocess_communicate_async().


[View source]
def communicate_utf8(stdin_buf : String | Nil, cancellable : Gio::Cancellable | Nil) : Bool #

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, stdout_buf and stderr_buf will be set to undefined values and should not be used.


[View source]
def communicate_utf8_async(stdin_buf : String | Nil, cancellable : Gio::Cancellable | Nil, &callback : Gio::AsyncReadyCallback) : Nil #

Asynchronous version of g_subprocess_communicate_utf8(). Complete invocation with g_subprocess_communicate_utf8_finish().


[View source]
def communicate_utf8_finish(result : Gio::AsyncResult) : Bool #

Complete an invocation of g_subprocess_communicate_utf8_async().


[View source]
def exit_status : Int32 #

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.


[View source]

[View source]
def force_exit : Nil #

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.


[View source]
def hash(hasher) #
Description copied from class Reference

See Object#hash(hasher)


def identifier : String | Nil #

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 return nil.


[View source]
def if_exited : Bool #

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.


[View source]
def if_signaled : Bool #

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.


[View source]
def send_signal(signal_num : Int32) : Nil #

Sends the UNIX signal signal_num to 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.


[View source]
def status : Int32 #

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.


[View source]
def stderr_pipe : Gio::InputStream | Nil #

Gets the #GInputStream from which to read the stderr output of subprocess.

The process must have been created with %G_SUBPROCESS_FLAGS_STDERR_PIPE, otherwise nil will be returned.


[View source]
def stdin_pipe : Gio::OutputStream | Nil #

Gets the #GOutputStream that you can write to in order to give data to the stdin of subprocess.

The process must have been created with %G_SUBPROCESS_FLAGS_STDIN_PIPE and not %G_SUBPROCESS_FLAGS_STDIN_INHERIT, otherwise nil will be returned.


[View source]
def stdout_pipe : Gio::InputStream | Nil #

Gets the #GInputStream from which to read the stdout output of subprocess.

The process must have been created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE, otherwise nil will be returned.


[View source]
def successful : Bool #

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.


[View source]
def term_sig : Int32 #

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.


[View source]
def wait(cancellable : Gio::Cancellable | Nil) : Bool #

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 cancellable doesn't kill the subprocess. Call g_subprocess_force_exit() if it is desirable.


[View source]
def wait_async(cancellable : Gio::Cancellable | Nil, &callback : Gio::AsyncReadyCallback) : Nil #

Wait for the subprocess to terminate.

This is the asynchronous version of g_subprocess_wait().


[View source]
def wait_check(cancellable : Gio::Cancellable | Nil) : Bool #

Combines g_subprocess_wait() with g_spawn_check_wait_status().


[View source]
def wait_check_async(cancellable : Gio::Cancellable | Nil, &callback : Gio::AsyncReadyCallback) : Nil #

Combines g_subprocess_wait_async() with g_spawn_check_wait_status().

This is the asynchronous version of g_subprocess_wait_check().


[View source]
def wait_check_finish(result : Gio::AsyncResult) : Bool #

Collects the result of a previous call to g_subprocess_wait_check_async().


[View source]
def wait_finish(result : Gio::AsyncResult) : Bool #

Collects the result of a previous call to g_subprocess_wait_async().


[View source]