Module Process
In: process.c

The Process module is a collection of methods used to manipulate processes.

Methods

abort   daemon   detach   egid   egid=   euid   euid=   exec   exit   exit!   fork   getpgid   getpgrp   getpriority   getrlimit   gid   gid=   groups   groups=   initgroups   kill   maxgroups   maxgroups=   pid   ppid   setpgid   setpgrp   setpriority   setrlimit   setsid   spawn   times   uid   uid=   wait   wait2   waitall   waitpid   waitpid2  

Classes and Modules

Module Process::GID
Module Process::Sys
Module Process::UID
Class Process::Status

Constants

WNOHANG = INT2FIX(WNOHANG)
WNOHANG = INT2FIX(0)
WUNTRACED = INT2FIX(WUNTRACED)
WUNTRACED = INT2FIX(0)
PRIO_PROCESS = INT2FIX(PRIO_PROCESS)
PRIO_PGRP = INT2FIX(PRIO_PGRP)
PRIO_USER = INT2FIX(PRIO_USER)
RLIM_INFINITY = inf
RLIM_SAVED_MAX = v
RLIM_SAVED_CUR = v
RLIMIT_CORE = INT2FIX(RLIMIT_CORE)
RLIMIT_CPU = INT2FIX(RLIMIT_CPU)
RLIMIT_DATA = INT2FIX(RLIMIT_DATA)
RLIMIT_FSIZE = INT2FIX(RLIMIT_FSIZE)
RLIMIT_NOFILE = INT2FIX(RLIMIT_NOFILE)
RLIMIT_STACK = INT2FIX(RLIMIT_STACK)
RLIMIT_AS = INT2FIX(RLIMIT_AS)
RLIMIT_MEMLOCK = INT2FIX(RLIMIT_MEMLOCK)
RLIMIT_NPROC = INT2FIX(RLIMIT_NPROC)
RLIMIT_RSS = INT2FIX(RLIMIT_RSS)
RLIMIT_SBSIZE = INT2FIX(RLIMIT_SBSIZE)

Public Class methods

Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.

Detach the process from controlling terminal and run in the background as system daemon. Unless the argument nochdir is true (i.e. non false), it changes the current working directory to the root ("/"). Unless the argument noclose is true, daemon() will redirect standard input, standard output and standard error to /dev/null.

Some operating systems retain the status of terminated child processes until the parent collects that status (normally using some variant of wait(). If the parent never collects this status, the child stays around as a zombie process. Process::detach prevents this by setting up a separate Ruby thread whose sole job is to reap the status of the process pid when it terminates. Use detach only when you do not intent to explicitly wait for the child to terminate.

The waiting thread returns the exit status of the detached process when it terminates, so you can use Thread#join to know the result. If specified pid is not a valid child process ID, the thread returns nil immediately.

In this first example, we don‘t reap the first child process, so it appears as a zombie in the process status display.

   p1 = fork { sleep 0.1 }
   p2 = fork { sleep 0.2 }
   Process.waitpid(p2)
   sleep 2
   system("ps -ho pid,state -p #{p1}")

produces:

   27389 Z

In the next example, Process::detach is used to reap the child automatically.

   p1 = fork { sleep 0.1 }
   p2 = fork { sleep 0.2 }
   Process.detach(p1)
   Process.waitpid(p2)
   sleep 2
   system("ps -ho pid,state -p #{p1}")

(produces no output)

Returns the effective group ID for this process. Not available on all platforms.

   Process.egid   #=> 500

Sets the effective group ID for this process. Not available on all platforms.

Returns the effective user ID for this process.

   Process.euid   #=> 501

Sets the effective user ID for this process. Not available on all platforms.

Replaces the current process by running the given external command. If optional arguments, sequence of arg, are not given, that argument is taken as a line that is subject to shell expansion before being executed. If one or more arg given, they are passed as parameters to command with no shell expansion. If command is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).

The hash arguments, env and options, are same as system and spawn. See spawn for details.

Raises SystemCallError if the command couldn‘t execute (typically Errno::ENOENT when it was not found).

   exec "echo *"       # echoes list of files in current directory
   # never get here

   exec "echo", "*"    # echoes an asterisk
   # never get here

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.

   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

Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.

   Process.exit!(0)

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

The thread calling fork is the only thread in the created child process. fork doesn‘t copy other threads.

Returns the process group ID for the given process id. Not available on all platforms.

   Process.getpgid(Process.ppid())   #=> 25527

Returns the process group ID for this process. Not available on all platforms.

   Process.getpgid(0)   #=> 25527
   Process.getpgrp      #=> 25527

Gets the scheduling priority for specified process, process group, or user. kind indicates the kind of entity to find: one of Process::PRIO_PGRP, Process::PRIO_USER, or Process::PRIO_PROCESS. integer is an id indicating the particular process, process group, or user (an id of 0 means current). Lower priorities are more favorable for scheduling. Not available on all platforms.

   Process.getpriority(Process::PRIO_USER, 0)      #=> 19
   Process.getpriority(Process::PRIO_PROCESS, 0)   #=> 19

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.

Returns the (real) group ID for this process.

   Process.gid   #=> 500

Sets the group ID for this process.

Get an Array of the gids of groups in the supplemental group access list for this process.

   Process.groups   #=> [27, 6, 10, 11]

Set the supplemental group access list to the given Array of group IDs.

   Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
   Process.groups = [27, 6, 10, 11]   #=> [27, 6, 10, 11]
   Process.groups   #=> [27, 6, 10, 11]

Initializes the supplemental group access list by reading the system group database and using all groups of which the given user is a member. The group with the specified gid is also added to the list. Returns the resulting Array of the gids of all the groups in the supplementary group access list. Not available on all platforms.

   Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
   Process.initgroups( "mgranger", 30 )   #=> [30, 6, 10, 11]
   Process.groups   #=> [30, 6, 10, 11]

Sends the given signal to the specified process id(s), or to the current process if pid is zero. signal may be an integer signal number or a POSIX signal name (either with or without a SIG prefix). If signal is negative (or starts with a minus sign), kills process groups instead of processes. Not all signals are available on all platforms.

   pid = fork do
      Signal.trap("HUP") { puts "Ouch!"; exit }
      # ... do some work ...
   end
   # ...
   Process.kill("HUP", pid)
   Process.wait

produces:

   Ouch!

Returns the maximum number of gids allowed in the supplemental group access list.

   Process.maxgroups   #=> 32

Sets the maximum number of gids allowed in the supplemental group access list.

Returns the process id of this process. Not available on all platforms.

   Process.pid   #=> 27415

Returns the process id of the parent of this process. Always returns 0 on NT. Not available on all platforms.

   puts "I am #{Process.pid}"
   Process.fork { puts "Dad is #{Process.ppid}" }

produces:

   I am 27417
   Dad is 27417

Sets the process group ID of pid (0 indicates this process) to integer. Not available on all platforms.

Equivalent to setpgid(0,0). Not available on all platforms.

See Process#getpriority.

   Process.setpriority(Process::PRIO_USER, 0, 19)      #=> 0
   Process.setpriority(Process::PRIO_PROCESS, 0, 19)   #=> 0
   Process.getpriority(Process::PRIO_USER, 0)          #=> 19
   Process.getpriority(Process::PRIO_PROCESS, 0)       #=> 19

Sets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit.

If max_limit is not given, cur_limit is used.

resource indicates the kind of resource to limit. It should be a symbol such as :CORE, a string such as "CORE" or a constant such as Process::RLIMIT_CORE. The available resources are OS dependent. Ruby may support following resources.

CORE
core size (bytes) (SUSv3)
CPU
CPU time (seconds) (SUSv3)
DATA
data segment (bytes) (SUSv3)
FSIZE
file size (bytes) (SUSv3)
NOFILE
file descriptors (number) (SUSv3)
STACK
stack size (bytes) (SUSv3)
AS
total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD but 4.4BSD-Lite)
MEMLOCK
total size for mlock(2) (bytes) (4.4BSD, GNU/Linux)
NPROC
number of processes for the user (number) (4.4BSD, GNU/Linux)
RSS
resident memory size (bytes) (4.2BSD, GNU/Linux)
SBSIZE
all socket buffers (bytes) (NetBSD, FreeBSD)

cur_limit and max_limit may be :INFINITY, "INFINITY" or Process::RLIM_INFINITY, which means that the resource is not limited. They may be Process::RLIM_SAVED_MAX, Process::RLIM_SAVED_CUR and corresponding symbols and strings too. See system setrlimit(2) manual for details.

The following example raise the soft limit of core size to the hard limit to try to make core dump possible.

  Process.setrlimit(:CORE, Process.getrlimit(:CORE)[1])

Establishes this process as a new session and process group leader, with no controlling tty. Returns the session id. Not available on all platforms.

   Process.setsid   #=> 27422

Similar to Kernel::system except for not waiting for end of cmd, but returns its pid.

If a hash is given as env, the environment is updated by env before exec(2) in the child process.

If a hash is given as options, it specifies 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 or positive integer. true and zero means the process should be a process leader. Other values specifies a process group to be belongs.

  pid = spawn(command, :pgroup=>true) # process leader
  pid = spawn(command, :pgroup=>10) # belongs to the process group 10

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.

  pid = spawn(command, :rlimit_core=>0) # never dump core.
  cur, max = Process.getrlimit(:CORE)
  pid = spawn(command, :rlimit_core=>[0,max]) # disable core temporary.
  pid = spawn(command, :rlimit_core=>max) # enable core dump

The :chdir key in options specifies the current directory.

  pid = spawn(command, :chdir=>"/var/tmp")

The :umask key in options specifies the umask.

  pid = spawn(command, :umask=>077)

The :in, :out, :err, a fixnum, an IO and an array key specifies a redirect. The redirection maps a file descriptor in the child process.

For example, stderr can be merged into stdout:

  pid = spawn(command, :err=>:out)
  pid = spawn(command, STDERR=>STDOUT)
  pid = spawn(command, 2=>1)

The hash keys specifies a file descriptor in the child process started by spawn. :err, STDERR and 2 specifies the standard error stream.

The hash values specifies a file descriptor in the parent process which invokes spawn. :out, STDOUT and 1 specifies the standard output stream.

The standard output in the child process is not specified. So it is inherited from the parent process.

The standard input stream can be specifed by :in, STDIN and 0.

A filename can be specified as a hash value.

  pid = spawn(command, STDIN=>"/dev/null") # read mode
  pid = spawn(command, STDOUT=>"/dev/null") # write mode
  pid = spawn(command, STDERR=>"log") # write mode
  pid = spawn(command, 3=>"/dev/null") # read mode

For standard output and standard error, 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, STDIN=>["file"]) # read mode is assumed
  pid = spawn(command, STDIN=>["file", "r"])
  pid = spawn(command, STDOUT=>["log", "w"]) # 0644 assumed
  pid = spawn(command, STDOUT=>["log", "w", 0600])
  pid = spawn(command, STDOUT=>["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 ommitted or nil, File::RDONLY is assumed. The permission should be an integer. If the permission is ommitted or nil, 0644 is assumed.

If an array of IOs and integers are specified as a hash key, all the elemetns are redirected.

  # standard output and standard error is redirected to log file.
  pid = spawn(command, [STDOUT, STDERR]=>["log", "w"])

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.

So IO.pipe and spawn can be used as IO.popen.

  # similar to r = IO.popen(command)
  r, w = IO.pipe
  pid = spawn(command, STDOUT=>w)   # r, w is closed in the child process.
  w.close

:close is specified as a hash value to close a fd individualy.

  f = open(foo)
  system(command, f=>:close)        # don't inherit f.

It is also possible to exchange file descriptors.

  pid = spawn(command, STDOUT=>STDERR, STDERR=>STDOUT)

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.

Returns a Tms structure (see Struct::Tms on page 388) that contains user and system CPU times for this process.

   t = Process.times
   [ t.utime, t.stime ]   #=> [0.0, 0.02]

Returns the (real) user ID of this process.

   Process.uid   #=> 501

Sets the (integer) user ID for this process. Not available on all platforms.

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:

> 0:Waits for the child whose process ID equals pid.
0:Waits for any child whose process group ID equals that of the calling process.
-1:Waits for any child process (the default if no pid is given).
< -1: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 SystemError 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 SystemError 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:

   [[27434, #<Process::Status: pid=27434,exited(0)>],
    [27433, #<Process::Status: pid=27433,exited(1)>],
    [27432, #<Process::Status: pid=27432,exited(2)>]]

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:

> 0:Waits for the child whose process ID equals pid.
0:Waits for any child whose process group ID equals that of the calling process.
-1:Waits for any child process (the default if no pid is given).
< -1: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 SystemError 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 SystemError if there are no child processes.

   Process.fork { exit 99 }   #=> 27437
   pid, status = Process.wait2
   pid                        #=> 27437
   status.exitstatus          #=> 99

[Validate]

ruby-doc.org is a community service provided by James Britt and Happy Camper Studios, a Phoenix, Arizona, Ruby application development company.

Documentation content on ruby-doc.org is provided by remarkable members of the Ruby community.

For more information on the Ruby programming language, visit ruby-lang.org.

Want to help improve Ruby's API docs? See Ruby Documentation Guidelines.