Exits the process immediately. No exit handlers are run. status is returned to the underlying system as the exit status.
Process.exit!(true)
spawn executes specified command and return its pid.
pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2") Process.wait pid pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'") Process.wait pid
This method is similar to Kernel#system
but it doesn’t wait for the command to finish.
The parent process should use Process.wait
to collect the termination status of its child or use Process.detach
to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.
spawn has bunch of options to specify process attributes:
env: hash name => val : set the environment variable name => nil : unset the environment variable the keys and the values except for +nil+ must be strings. command...: commandline : command line string which is passed to the standard shell cmdname, arg1, ... : command name and one or more arguments (This form does not use the shell. See below for caveats.) [cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments (no shell) options: hash clearing environment variables: :unsetenv_others => true : clear environment variables except specified by env :unsetenv_others => false : don't clear (default) process group: :pgroup => true or 0 : make a new process group :pgroup => pgid : join the specified process group :pgroup => nil : don't change the process group (default) create new process group: Windows only :new_pgroup => true : the new process is the root process of a new process group :new_pgroup => false : don't create a new process group (default) resource limit: resourcename is core, cpu, data, etc. See Process.setrlimit. :rlimit_resourcename => limit :rlimit_resourcename => [cur_limit, max_limit] umask: :umask => int redirection: key: FD : single file descriptor in child process [FD, FD, ...] : multiple file descriptor in child process value: FD : redirect to the file descriptor in parent process string : redirect to file with open(string, "r" or "w") [string] : redirect to file with open(string, File::RDONLY) [string, open_mode] : redirect to file with open(string, open_mode, 0644) [string, open_mode, perm] : redirect to file with open(string, open_mode, perm) [:child, FD] : redirect to the redirected file descriptor :close : close the file descriptor in child process FD is one of follows :in : the file descriptor 0 which is the standard input :out : the file descriptor 1 which is the standard output :err : the file descriptor 2 which is the standard error integer : the file descriptor of specified the integer io : the file descriptor specified as io.fileno file descriptor inheritance: close non-redirected non-standard fds (3, 4, 5, ...) or not :close_others => false : inherit current directory: :chdir => str
The cmdname, arg1, ...
form does not use the shell. However, on different OSes, different things are provided as built-in commands. An example of this is +‘echo’+, which is a built-in on Windows, but is a normal program on Linux and Mac OS X. This means that Process.spawn 'echo', '%Path%'
will display the contents of the %Path%
environment variable on Windows, but Process.spawn 'echo', '$PATH'
prints the literal $PATH
.
If a hash is given as env
, the environment is updated by env
before exec(2)
in the child process. If a pair in env
has nil as the value, the variable is deleted.
# set FOO as BAR and unset BAZ. pid = spawn({"FOO"=>"BAR", "BAZ"=>nil}, command)
If a hash is given as options
, it specifies process group, create new process group, resource limit, current directory, umask and redirects for the child process. Also, it can be specified to clear environment variables.
The :unsetenv_others
key in options
specifies to clear environment variables, other than specified by env
.
pid = spawn(command, :unsetenv_others=>true) # no environment variable pid = spawn({"FOO"=>"BAR"}, command, :unsetenv_others=>true) # FOO only
The :pgroup
key in options
specifies a process group. The corresponding value should be true, zero, a positive integer, or nil. true and zero cause the process to be a process leader of a new process group. A non-zero positive integer causes the process to join the provided process group. The default value, nil, causes the process to remain in the same process group.
pid = spawn(command, :pgroup=>true) # process leader pid = spawn(command, :pgroup=>10) # belongs to the process group 10
The :new_pgroup
key in options
specifies to pass CREATE_NEW_PROCESS_GROUP
flag to CreateProcessW()
that is Windows API. This option is only for Windows. true means the new process is the root process of the new process group. The new process has CTRL+C disabled. This flag is necessary for Process.kill(:SIGINT, pid)
on the subprocess. :new_pgroup is false by default.
pid = spawn(command, :new_pgroup=>true) # new process group pid = spawn(command, :new_pgroup=>false) # same process group
The :rlimit_
foo key specifies a resource limit. foo should be one of resource types such as core
. The corresponding value should be an integer or an array which have one or two integers: same as cur_limit and max_limit arguments for Process.setrlimit
.
cur, max = Process.getrlimit(:CORE) pid = spawn(command, :rlimit_core=>[0,max]) # disable core temporary. pid = spawn(command, :rlimit_core=>max) # enable core dump pid = spawn(command, :rlimit_core=>0) # never dump core.
The :umask
key in options
specifies the umask.
pid = spawn(command, :umask=>077)
The :in, :out, :err, an integer, an IO
and an array key specifies a redirection. The redirection maps a file descriptor in the child process.
For example, stderr can be merged into stdout as follows:
pid = spawn(command, :err=>:out) pid = spawn(command, 2=>1) pid = spawn(command, STDERR=>:out) pid = spawn(command, STDERR=>STDOUT)
The hash keys specifies a file descriptor in the child process started by spawn
. :err, 2 and STDERR specifies the standard error stream (stderr).
The hash values specifies a file descriptor in the parent process which invokes spawn
. :out, 1 and STDOUT specifies the standard output stream (stdout).
In the above example, the standard output in the child process is not specified. So it is inherited from the parent process.
The standard input stream (stdin) can be specified by :in, 0 and STDIN.
A filename can be specified as a hash value.
pid = spawn(command, :in=>"/dev/null") # read mode pid = spawn(command, :out=>"/dev/null") # write mode pid = spawn(command, :err=>"log") # write mode pid = spawn(command, [:out, :err]=>"/dev/null") # write mode pid = spawn(command, 3=>"/dev/null") # read mode
For stdout and stderr (and combination of them), it is opened in write mode. Otherwise read mode is used.
For specifying flags and permission of file creation explicitly, an array is used instead.
pid = spawn(command, :in=>["file"]) # read mode is assumed pid = spawn(command, :in=>["file", "r"]) pid = spawn(command, :out=>["log", "w"]) # 0644 assumed pid = spawn(command, :out=>["log", "w", 0600]) pid = spawn(command, :out=>["log", File::WRONLY|File::EXCL|File::CREAT, 0600])
The array specifies a filename, flags and permission. The flags can be a string or an integer. If the flags is omitted or nil, File::RDONLY is assumed. The permission should be an integer. If the permission is omitted or nil, 0644 is assumed.
If an array of IOs and integers are specified as a hash key, all the elements are redirected.
# stdout and stderr is redirected to log file. # The file "log" is opened just once. pid = spawn(command, [:out, :err]=>["log", "w"])
Another way to merge multiple file descriptors is [:child, fd]. [:child, fd] means the file descriptor in the child process. This is different from fd. For example, :err=>:out means redirecting child stderr to parent stdout. But :err=>[:child, :out] means redirecting child stderr to child stdout. They differ if stdout is redirected in the child process as follows.
# stdout and stderr is redirected to log file. # The file "log" is opened just once. pid = spawn(command, :out=>["log", "w"], :err=>[:child, :out])
[:child, :out] can be used to merge stderr into stdout in IO.popen
. In this case, IO.popen
redirects stdout to a pipe in the child process and [:child, :out] refers the redirected stdout.
io = IO.popen(["sh", "-c", "echo out; echo err >&2", :err=>[:child, :out]]) p io.read #=> "out\nerr\n"
The :chdir
key in options
specifies the current directory.
pid = spawn(command, :chdir=>"/var/tmp")
spawn closes all non-standard unspecified descriptors by default. The “standard” descriptors are 0, 1 and 2. This behavior is specified by :close_others option. :close_others doesn’t affect the standard descriptors which are closed only if :close is specified explicitly.
pid = spawn(command, :close_others=>true) # close 3,4,5,... (default) pid = spawn(command, :close_others=>false) # don't close 3,4,5,...
:close_others is false by default for spawn and IO.popen
.
Note that fds which close-on-exec flag is already set are closed regardless of :close_others option.
So IO.pipe
and spawn can be used as IO.popen
.
# similar to r = IO.popen(command) r, w = IO.pipe pid = spawn(command, :out=>w) # r, w is closed in the child process. w.close
:close is specified as a hash value to close a fd individually.
f = open(foo) system(command, f=>:close) # don't inherit f.
If a file descriptor need to be inherited, io=>io can be used.
# valgrind has --log-fd option for log destination. # log_w=>log_w indicates log_w.fileno inherits to child process. log_r, log_w = IO.pipe pid = spawn("valgrind", "--log-fd=#{log_w.fileno}", "echo", "a", log_w=>log_w) log_w.close p log_r.read
It is also possible to exchange file descriptors.
pid = spawn(command, :out=>:err, :err=>:out)
The hash keys specify file descriptors in the child process. The hash values specifies file descriptors in the parent process. So the above specifies exchanging stdout and stderr. Internally, spawn
uses an extra file descriptor to resolve such cyclic file descriptor mapping.
See Kernel.exec
for the standard shell.
Initiates the termination of the Ruby script by raising the SystemExit
exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment. true
and FALSE
of status means success and failure respectively. The interpretation of other integer values are system dependent.
begin exit puts "never get here" rescue SystemExit puts "rescued a SystemExit exception" end puts "after begin block"
produces:
rescued a SystemExit exception after begin block
Just prior to termination, Ruby executes any at_exit
functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer
).
at_exit { puts "at_exit function" } ObjectSpace.define_finalizer("string", proc { puts "in finalizer" }) exit
produces:
at_exit function in finalizer
Terminate execution immediately, effectively by calling Kernel.exit(false)
. If msg is given, it is written to STDERR prior to terminating.
Deprecated. Use block_given? instead.
If warnings have been disabled (for example with the -W0
flag), does nothing. Otherwise, converts each of the messages to strings, appends a newline character to the string if the string does not end in a newline, and calls Warning.warn
with the string.
warn("warning 1", "warning 2") <em>produces:</em> warning 1 warning 2
If the uplevel
keyword argument is given, the string will be prepended with information for the given caller frame in the same format used by the rb_warn
C function.
# In baz.rb def foo warn("invalid call to foo", uplevel: 1) end def bar foo end bar <em>produces:</em> baz.rb:6: warning: invalid call to foo
If category
keyword argument is given, passes the category to Warning.warn
. The category given must be be one of the following categories:
Used for warning for deprecated functionality that may be removed in the future.
Used for experimental features that may change in future releases.
Returns an array containing the sorted elements of self
. The ordering of equal elements is indeterminate and may be unstable.
With no block given, the sort compares using the elements’ own method <=>
:
%w[b c a d].sort # => ["a", "b", "c", "d"] {foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]
With a block given, comparisons in the block determine the ordering. The block is called with two elements a
and b
, and must return:
A negative integer if a < b
.
Zero if a == b
.
A positive integer if a > b
.
Examples:
a = %w[b c a d] a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"] h = {foo: 0, bar: 1, baz: 2} h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]
See also sort_by
. It implements a Schwartzian transform which is useful when key computation or comparison is expensive.
Returns whether exactly one element meets a given criterion.
With no argument and no block, returns whether exactly one element is truthy:
(1..1).one? # => true [1, nil, false].one? # => true (1..4).one? # => false {foo: 0}.one? # => true {foo: 0, bar: 1}.one? # => false [].one? # => false
With argument pattern
and no block, returns whether for exactly one element element
, pattern === element
:
[nil, false, 0].one?(Integer) # => true [nil, false, 0].one?(Numeric) # => true [nil, false, 0].one?(Float) # => false %w[bar baz bat bam].one?(/m/) # => true %w[bar baz bat bam].one?(/foo/) # => false %w[bar baz bat bam].one?('ba') # => false {foo: 0, bar: 1, baz: 2}.one?(Array) # => false {foo: 0}.one?(Array) # => true [].one?(Integer) # => false
With a block given, returns whether the block returns a truthy value for exactly one element:
(1..4).one? {|element| element < 2 } # => true (1..4).one? {|element| element < 1 } # => false {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
Returns whether no element meets a given criterion.
With no argument and no block, returns whether no element is truthy:
(1..4).none? # => false [nil, false].none? # => true {foo: 0}.none? # => false {foo: 0, bar: 1}.none? # => false [].none? # => true
With argument pattern
and no block, returns whether for no element element
, pattern === element
:
[nil, false, 1.1].none?(Integer) # => true %w[bar baz bat bam].none?(/m/) # => false %w[bar baz bat bam].none?(/foo/) # => true %w[bar baz bat bam].none?('ba') # => true {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true {foo: 0}.none?(Array) # => false [].none?(Integer) # => true
With a block given, returns whether the block returns a truthy value for no element:
(1..4).none? {|element| element < 1 } # => true (1..4).none? {|element| element < 2 } # => false {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
Returns an array of all non-nil
elements:
a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil] a.compact # => [0, "a", false, false, "a", 0]
Writes warning message msg
to $stderr. This method is called by Ruby for all emitted warnings. A category
may be included with the warning.
See the documentation of the Warning
module for how to customize this.
Computes the square root of decimal
to the specified number of digits of precision, numeric
.
BigMath.sqrt(BigDecimal('2'), 16).to_s #=> "0.1414213562373095048801688724e1"
Provides a convenient Ruby iterator which executes a block for each entry in the /etc/passwd file.
The code block is passed an Passwd
struct.
See ::getpwent
above for details.
Example:
require 'etc' Etc.passwd {|u| puts u.name + " = " + u.gecos }
Returns system configuration directory.
This is typically “/etc”, but is modified by the prefix used when Ruby was compiled. For example, if Ruby is built and installed in /usr/local, returns “/usr/local/etc” on other platforms than Windows. On Windows, this always returns the directory provided by the system.
Returns system configuration variable using sysconf().
name should be a constant under Etc
which begins with SC_
.
The return value is an integer or nil. nil means indefinite limit. (sysconf() returns -1 but errno is not set.)
Etc.sysconf(Etc::SC_ARG_MAX) #=> 2097152 Etc.sysconf(Etc::SC_LOGIN_NAME_MAX) #=> 256
Returns system configuration variable using confstr().
name should be a constant under Etc
which begins with CS_
.
The return value is a string or nil. nil means no configuration-defined value. (confstr() returns 0 but errno is not set.)
Etc.confstr(Etc::CS_PATH) #=> "/bin:/usr/bin" # GNU/Linux Etc.confstr(Etc::CS_GNU_LIBC_VERSION) #=> "glibc 2.18" Etc.confstr(Etc::CS_GNU_LIBPTHREAD_VERSION) #=> "NPTL 2.18"
Encodes string using String.encode
.
Spawns the specified command on a newly allocated pty. You can also use the alias ::getpty
.
The command’s controlling tty is set to the slave device of the pty and its standard input/output/error is redirected to the slave device.
command
and command_line
are the full commands to run, given a String
. Any additional arguments
will be passed to the command.
In the non-block form this returns an array of size three, [r, w, pid]
.
In the block form these same values will be yielded to the block:
Returns the facility number used in the last call to open()
Returns true
if the named file is writable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the effective user/group.
Returns true
if the named file is a character device.
file_name can be an IO
object.
This function compacts objects together in Ruby’s heap. It eliminates unused space (or fragmentation) in the heap by moving objects in to that unused space. This function returns a hash which contains statistics about which objects were moved. See ‘GC.latest_gc_info` for details about compaction statistics.
This method is implementation specific and not expected to be implemented in any implementation besides MRI.