URI::split(uri)
uri
String with URI
.
Splits the string on following parts and returns array with result:
* Scheme * Userinfo * Host * Port * Registry * Path * Opaque * Query * Fragment
require 'uri' p URI.split("http://www.ruby-lang.org/") # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
Retrieve the PathSupport
object that RubyGems uses to lookup files.
Initialize the filesystem paths to use from env
. env
is a hash-like object (typically ENV
) that is queried for ‘GEM_HOME’, ‘GEM_PATH’, and ‘GEM_SPEC_CACHE’ Keys for the env
hash should be Strings, and values of the hash should be Strings or nil
.
Allows setting the gem path searcher. This method is available when requiring ‘rubygems/test_case’
Splits a string into an array of tokens in the same way the UNIX Bourne shell does.
argv = Shellwords.split('here are "two words"') argv #=> ["here", "are", "two words"]
Note, however, that this is not a command line parser. Shell
metacharacters except for the single and double quotes and backslash are not treated as such.
argv = Shellwords.split('ruby my_prog.rb | less') argv #=> ["ruby", "my_prog.rb", "|", "less"]
String#shellsplit
is a shortcut for this function.
argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]
Splits a string into an array of tokens in the same way the UNIX Bourne shell does.
argv = Shellwords.split('here are "two words"') argv #=> ["here", "are", "two words"]
Note, however, that this is not a command line parser. Shell
metacharacters except for the single and double quotes and backslash are not treated as such.
argv = Shellwords.split('ruby my_prog.rb | less') argv #=> ["ruby", "my_prog.rb", "|", "less"]
String#shellsplit
is a shortcut for this function.
argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]
Raises a TypeError
to prevent cloning.
Returns a topologically sorted array of nodes. The array is sorted from children to parents, i.e. the first element has no child and the last node has no parent.
If there is a cycle, TSort::Cyclic
is raised.
class G include TSort def initialize(g) @g = g end def tsort_each_child(n, &b) @g[n].each(&b) end def tsort_each_node(&b) @g.each_key(&b) end end graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}) p graph.tsort #=> [4, 2, 3, 1] graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}) p graph.tsort # raises TSort::Cyclic
Returns a topologically sorted array of nodes. The array is sorted from children to parents, i.e. the first element has no child and the last node has no parent.
The graph is represented by each_node and each_child. each_node should have call
method which yields for each node in the graph. each_child should have call
method which takes a node argument and yields for each child node.
If there is a cycle, TSort::Cyclic
is raised.
g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]} each_node = lambda {|&b| g.each_key(&b) } each_child = lambda {|n, &b| g[n].each(&b) } p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1] g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]} each_node = lambda {|&b| g.each_key(&b) } each_child = lambda {|n, &b| g[n].each(&b) } p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
Returns the non-negative square root of x
.
Domain: [0, INFINITY)
Codomain:[0, INFINITY)
0.upto(10) {|x| p [x, Math.sqrt(x), Math.sqrt(x)**2] } #=> [0, 0.0, 0.0] # [1, 1.0, 1.0] # [2, 1.4142135623731, 2.0] # [3, 1.73205080756888, 3.0] # [4, 2.0, 4.0] # [5, 2.23606797749979, 5.0] # [6, 2.44948974278318, 6.0] # [7, 2.64575131106459, 7.0] # [8, 2.82842712474619, 8.0] # [9, 3.0, 9.0] # [10, 3.16227766016838, 10.0]
Note that the limited precision of floating point arithmetic might lead to surprising results:
Math.sqrt(10**46).to_i #=> 99999999999999991611392 (!)
See also BigDecimal#sqrt
and Integer.sqrt
.
Returns the cube root of x
.
Domain: (-INFINITY, INFINITY)
Codomain: (-INFINITY, INFINITY)
-9.upto(9) {|x| p [x, Math.cbrt(x), Math.cbrt(x)**3] } #=> [-9, -2.0800838230519, -9.0] # [-8, -2.0, -8.0] # [-7, -1.91293118277239, -7.0] # [-6, -1.81712059283214, -6.0] # [-5, -1.7099759466767, -5.0] # [-4, -1.5874010519682, -4.0] # [-3, -1.44224957030741, -3.0] # [-2, -1.25992104989487, -2.0] # [-1, -1.0, -1.0] # [0, 0.0, 0.0] # [1, 1.0, 1.0] # [2, 1.25992104989487, 2.0] # [3, 1.44224957030741, 3.0] # [4, 1.5874010519682, 4.0] # [5, 1.7099759466767, 5.0] # [6, 1.81712059283214, 6.0] # [7, 1.91293118277239, 7.0] # [8, 2.0, 8.0] # [9, 2.0800838230519, 9.0]
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 => true : don't 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 true 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.
Exits the process immediately. No exit handlers are run. status is returned to the underlying system as the exit status.
Process.exit!(true)
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.
Waits for a child process to exit, returns its process id, and sets $?
to a Process::Status
object containing information on that process. Which child it waits on depends on the value of pid:
Waits for the child whose process ID equals pid.
Waits for any child whose process group ID equals that of the calling process.
Waits for any child process (the default if no pid is given).
Waits for any child whose process group ID equals the absolute value of pid.
The flags argument may be a logical or of the flag values Process::WNOHANG
(do not block if no child available) or Process::WUNTRACED
(return stopped children that haven’t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.
Calling this method raises a SystemCallError
if there are no child processes. Not available on all platforms.
include Process fork { exit 99 } #=> 27429 wait #=> 27429 $?.exitstatus #=> 99 pid = fork { sleep 3 } #=> 27440 Time.now #=> 2008-03-08 19:56:16 +0900 waitpid(pid, Process::WNOHANG) #=> nil Time.now #=> 2008-03-08 19:56:16 +0900 waitpid(pid, 0) #=> 27440 Time.now #=> 2008-03-08 19:56:19 +0900
Waits for a child process to exit (see Process::waitpid
for exact semantics) and returns an array containing the process id and the exit status (a Process::Status
object) of that child. Raises a SystemCallError
if there are no child processes.
Process.fork { exit 99 } #=> 27437 pid, status = Process.wait2 pid #=> 27437 status.exitstatus #=> 99
Waits for a child process to exit, returns its process id, and sets $?
to a Process::Status
object containing information on that process. Which child it waits on depends on the value of pid:
Waits for the child whose process ID equals pid.
Waits for any child whose process group ID equals that of the calling process.
Waits for any child process (the default if no pid is given).
Waits for any child whose process group ID equals the absolute value of pid.
The flags argument may be a logical or of the flag values Process::WNOHANG
(do not block if no child available) or Process::WUNTRACED
(return stopped children that haven’t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.
Calling this method raises a SystemCallError
if there are no child processes. Not available on all platforms.
include Process fork { exit 99 } #=> 27429 wait #=> 27429 $?.exitstatus #=> 99 pid = fork { sleep 3 } #=> 27440 Time.now #=> 2008-03-08 19:56:16 +0900 waitpid(pid, Process::WNOHANG) #=> nil Time.now #=> 2008-03-08 19:56:16 +0900 waitpid(pid, 0) #=> 27440 Time.now #=> 2008-03-08 19:56:19 +0900
Waits for a child process to exit (see Process::waitpid
for exact semantics) and returns an array containing the process id and the exit status (a Process::Status
object) of that child. Raises a SystemCallError
if there are no child processes.
Process.fork { exit 99 } #=> 27437 pid, status = Process.wait2 pid #=> 27437 status.exitstatus #=> 99
Waits for all children, returning an array of pid/status pairs (where status is a Process::Status
object).
fork { sleep 0.2; exit 2 } #=> 27432 fork { sleep 0.1; exit 1 } #=> 27433 fork { exit 0 } #=> 27434 p Process.waitall
produces:
[[30982, #<Process::Status: pid 30982 exit 0>], [30979, #<Process::Status: pid 30979 exit 1>], [30976, #<Process::Status: pid 30976 exit 2>]]
Gets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit.
resource indicates the kind of resource to limit. It is specified as a symbol such as :CORE
, a string such as "CORE"
or a constant such as Process::RLIMIT_CORE
. See Process.setrlimit
for details.
cur_limit and max_limit may be Process::RLIM_INFINITY
, Process::RLIM_SAVED_MAX
or Process::RLIM_SAVED_CUR
. See Process.setrlimit
and the system getrlimit(2) manual for details.