class Process

Defined in:

kernel.cr
process.cr:1
process.cr:14
process/executable_path.cr:5
process/executable_path.cr:105
process/shell.cr

Constant Summary

PATH_DELIMITER = ':'

Constructors

Class Method Summary

Instance Method Summary

Instance methods inherited from class Reference

==(other : self)
==(other : JSON::Any)
==(other : YAML::Any)
==(other)
==
, dup dup, hash(hasher) hash, initialize initialize, inspect(io : IO) : Nil inspect, object_id : UInt64 object_id, pretty_print(pp) : Nil pretty_print, same?(other : Reference) : Bool
same?(other : Nil)
same?
, to_s(io : IO) : Nil to_s

Constructor methods inherited from class Reference

new new

Instance methods inherited from class Object

! : Bool !, !=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other)
===
, =~(other) =~, as(type : Class) as, as?(type : Class) as?, class class, dup dup, hash(hasher)
hash
hash
, in?(collection : Object) : Bool
in?(*values : Object) : Bool
in?
, inspect(io : IO) : Nil
inspect : String
inspect
, is_a?(type : Class) : Bool is_a?, itself itself, nil? : Bool nil?, not_nil!(message)
not_nil!
not_nil!
, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, responds_to?(name : Symbol) : Bool responds_to?, tap(&) tap, to_json(io : IO) : Nil
to_json : String
to_json
, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil
to_pretty_json
, to_s(io : IO) : Nil
to_s : String
to_s
, to_yaml(io : IO) : Nil
to_yaml : String
to_yaml
, try(&) try, unsafe_as(type : T.class) forall T unsafe_as

Class methods inherited from class Object

from_json(string_or_io, root : String)
from_json(string_or_io)
from_json
, from_yaml(string_or_io : String | IO) from_yaml

Constructor Detail

def self.new(command : String, args = nil, env : Env = nil, clear_env : Bool = false, shell : Bool = false, input : Stdio = Redirect::Close, output : Stdio = Redirect::Close, error : Stdio = Redirect::Close, chdir : Path | String | Nil = nil) #

Creates a process, executes it, but doesn't wait for it to complete.

To wait for it to finish, invoke #wait.

By default the process is configured without input, output or error.

If shell is false, the command is the path to the executable to run, along with a list of args.

If shell is true, the command should be the full command line including space-separated args.

  • On POSIX this uses /bin/sh to process the command string. args are also passed to the shell, and you need to include the string "${@}" in the command to safely insert them there.
  • On Windows this is implemented by passing the string as-is to the process, and passing args is not supported.

Raises IO::Error if executing the command fails (for example if the executable doesn't exist).


[View source]

Class Method Detail

def self.chroot(path : String) : Nil #

Changes the root directory and the current working directory for the current process.

Available only on Unix-like operating systems.

Security: .chroot on its own is not an effective means of mitigation. At minimum the process needs to also drop privileges as soon as feasible after the .chroot. Changes to the directory hierarchy or file descriptors passed via recvmsg(2) from outside the .chroot jail may allow a restricted process to escape, even if it is unprivileged.

Process.chroot("/var/empty")

[View source]
def self.exec(command : String, args = nil, env : Env = nil, clear_env : Bool = false, shell : Bool = false, input : ExecStdio = Redirect::Inherit, output : ExecStdio = Redirect::Inherit, error : ExecStdio = Redirect::Inherit, chdir : Path | String | Nil = nil) : NoReturn #

Replaces the current process with a new one. This function never returns.

Raises IO::Error if executing the command fails (for example if the executable doesn't exist).


[View source]
def self.executable_path : String | Nil #

Returns an absolute path to the executable file of the currently running program. This is in opposition to PROGRAM_NAME which may be a relative or absolute path, just the executable file name or a symlink.

The executable path will be canonicalized (all symlinks and relative paths will be expanded).

Returns nil if the file can't be found.


[View source]
def self.exists?(pid : Int) : Bool #

Returns true if the process identified by pid is valid for a currently registered process, false otherwise. Note that this returns true for a process in the zombie or similar state.


[View source]
def self.exit(status = 0) : NoReturn #

Terminate the current process immediately. All open files, pipes and sockets are flushed and closed, all child processes are inherited by PID 1. This does not run any handlers registered with at_exit, use ::exit for that.

status is the exit status of the current process.


[View source]
def self.find_executable(name : Path | String, path : String | Nil = ENV["PATH"]?, pwd : Path | String = Dir.current) : String | Nil #

Searches an executable, checking for an absolute path, a path relative to pwd or absolute path, then eventually searching in directories declared in path.


[View source]
def self.ignore_interrupts! : Nil #

Ignores all interrupt requests. Removes any custom interrupt handler set with #on_interrupt.

  • On Windows, interrupts generated by Ctrl + Break cannot be ignored in this way.

[View source]
def self.on_interrupt(&handler : -> ) : Nil #

Installs handler as the new handler for interrupt requests. Removes any previously set interrupt handler.

The handler is executed on a fresh fiber every time an interrupt occurs.

  • On Unix-like systems, this traps SIGINT.
  • On Windows, this captures Ctrl + C and Ctrl + Break signals sent to a console application.

[View source]
def self.parse_arguments(line : String) : Array(String) #

Splits the given line into individual command-line arguments in a platform-specific manner, unquoting tokens if necessary.

Equivalent to .parse_arguments_posix on Unix-like systems. Equivalent to .parse_arguments_windows on Windows.


[View source]
def self.parse_arguments_posix(line : String) : Array(String) #

Splits the given line into individual command-line arguments according to POSIX shell rules, unquoting tokens if necessary.

Raises ArgumentError if a quotation mark is unclosed.

Process.parse_arguments_posix(%q["foo bar" '\hello/' Fizz\ Buzz]) # => ["foo bar", "\\hello/", "Fizz Buzz"]

See https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_03


[View source]
def self.parse_arguments_windows(line : String) : Array(String) #

Splits the given line into individual command-line arguments according to Microsoft's standard C runtime, unquoting tokens if necessary.

Raises ArgumentError if a quotation mark is unclosed. Leading spaces in line are ignored. Otherwise, this method is equivalent to CommandLineToArgvW for some unspecified program name.

NOTE This does not take strings that are passed to the CMD shell or used in a batch script.

Process.parse_arguments_windows(%q[foo"bar \\\"hello\\" Fizz\Buzz]) # => ["foobar \\\"hello\\", "Fizz\\Buzz"]

[View source]
def self.pgid(pid : Int) : Int64 #

Returns the process group identifier of the process identified by pid.


[View source]
def self.pgid : Int64 #

Returns the process group identifier of the current process.


[View source]
def self.pid : Int64 #

Returns the process identifier of the current process.


[View source]
def self.ppid : Int64 #

Returns the process identifier of the parent process of the current process.

On Windows, the parent is associated only at process creation time, and the system does not re-parent the current process if the parent terminates; thus Process.exists?(Process.ppid) is not guaranteed to be true.


[View source]
def self.quote(args : Enumerable(String)) : String #

Converts a sequence of strings to one joined string with each argument shell-quoted.

This is then safe to pass as part of the command when using shell: true or system().

NOTE The actual return value is system-dependent, so it mustn't be relied on in other contexts. See also: .quote_posix.

files = ["my file.txt", "another.txt"]
`grep -E 'fo+' -- #{Process.quote(files)}`

[View source]
def self.quote(arg : String) : String #

Shell-quotes one item, same as .quote({arg}).


[View source]
def self.quote_posix(args : Enumerable(String)) : String #

Converts a sequence of strings to one joined string with each argument shell-quoted.

This is then safe to pass to a POSIX shell.

files = ["my file.txt", "another.txt"]
Process.quote_posix(files) # => "'my file.txt' another.txt"

[View source]
def self.quote_posix(arg : String) : String #

Shell-quotes one item, same as .quote_posix({arg}).


[View source]
def self.restore_interrupts! : Nil #

Restores default handling of interrupt requests.


[View source]
def self.run(command : String, args = nil, env : Env = nil, clear_env : Bool = false, shell : Bool = false, input : Stdio = Redirect::Close, output : Stdio = Redirect::Close, error : Stdio = Redirect::Close, chdir : Path | String | Nil = nil) : Process::Status #

Executes a process and waits for it to complete.

By default the process is configured without input, output or error.

Raises IO::Error if executing the command fails (for example if the executable doesn't exist).


[View source]
def self.run(command : String, args = nil, env : Env = nil, clear_env : Bool = false, shell : Bool = false, input : Stdio = Redirect::Pipe, output : Stdio = Redirect::Pipe, error : Stdio = Redirect::Pipe, chdir : Path | String | Nil = nil, &) #

Executes a process, yields the block, and then waits for it to finish.

By default the process is configured to use pipes for input, output and error. These will be closed automatically at the end of the block.

Returns the block's value.

Raises IO::Error if executing the command fails (for example if the executable doesn't exist).


[View source]
def self.signal(signal : Signal, pid : Int) : Nil #

Sends signal to the process identified by pid.


[View source]
def self.times : Tms #

Returns a Tms for the current process. For the children times, only those of terminated children are returned on Unix; they are zero on Windows.


[View source]

Instance Method Detail

def close : Nil #

Closes any system resources (e.g. pipes) held for the child process.


[View source]
def error : IO::FileDescriptor #

A pipe to this process' error. Raises if a pipe wasn't asked when creating the process.


[View source]
def error? : IO::FileDescriptor | Nil #

A pipe to this process' error. Raises if a pipe wasn't asked when creating the process.


[View source]
def exists? : Bool #

Whether the process is still registered in the system. Note that this returns true for processes in the zombie or similar state.


[View source]
def finalize #

[View source]
def input : IO::FileDescriptor #

A pipe to this process' input. Raises if a pipe wasn't asked when creating the process.


[View source]
def input? : IO::FileDescriptor | Nil #

A pipe to this process' input. Raises if a pipe wasn't asked when creating the process.


[View source]
def output : IO::FileDescriptor #

A pipe to this process' output. Raises if a pipe wasn't asked when creating the process.


[View source]
def output? : IO::FileDescriptor | Nil #

A pipe to this process' output. Raises if a pipe wasn't asked when creating the process.


[View source]
def pid : Int64 #

Returns the process identifier of this process.


[View source]
def signal(signal : Signal) : Nil #

Sends signal to this process.

NOTE #terminate is preferred over #signal(Signal::TERM) and #signal(Signal::KILL) as a portable alternative which also works on Windows.


[View source]
def terminate(*, graceful : Bool = true) : Nil #

Asks this process to terminate.

If graceful is true, prefers graceful termination over abrupt termination if supported by the system.

  • On Unix-like systems, this causes Signal::TERM to be sent to the process instead of Signal::KILL.
  • On Windows, this parameter has no effect and graceful termination is unavailable. The terminated process has an exit status of 1.

[View source]
def terminated? : Bool #

Whether this process is already terminated.


[View source]
def wait : Process::Status #

Waits for this process to complete and closes any pipes.


[View source]