Ruby/Справочник/Process

Класс ProcessПравить

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


Примеси

Windows::Console (AddConsoleAlias, AllocConsole, AttachConsole, CreateConsoleScreenBuffer, FillConsoleOutputAttribute, FlushConsoleInputBuffer, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleAliasExes, GetConsoleAliasExesLength, GetConsoleAliases, GetConsoleAliasesLength, GetConsoleCP, GetConsoleCursorInfo, GetConsoleDisplayMode, GetConsoleFontSize, GetConsoleMode, GetConsoleOutputCP, GetConsoleProcessList, GetConsoleScreenBufferInfo, GetConsoleSelectionInfo, GetConsoleTitle, GetConsoleWindow, GetCurrentConsoleFont, GetLargestConsoleWindowSize, GetNumberOfConsoleInputEvents, GetNumberOfConsoleMouseButtons, GetStdHandle, PeekConsoleInput, ReadConsole, ReadConsoleInput, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, ScrollConsoleScreenBuffer, SetConsoleActiveScreenBuffer, SetConsoleCP, SetConsoleCommandHistoryMode, SetConsoleCtrlHandler, SetConsoleCursorInfo, SetConsoleCursorPosition, SetConsoleDisplayMode, SetConsoleHistoryInfo, SetConsoleMode, SetConsoleOutputCP, SetConsoleScreenBufferSize, SetConsoleTextAttribute, SetConsoleTitle, SetConsoleWindowInfo, SetStdHandle, WriteConsole, WriteConsoleInput, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter),

Windows::Error (FormatMessage, FormatMessageW, GetLastError, SetErrorMode, SetLastError, SetLastErrorEx, get_last_error),

Windows::Handle (CloseHandle, DuplicateHandle, GetHandleInformation, SetHandleInformation, get_osfhandle, open_osfhandle),

Windows::Library (DisableThreadLibraryCalls, FreeLibrary, GetDllDirectory, GetModuleFileName, GetModuleHandle, GetModuleHandleEx, GetProcAddress, LoadLibrary, LoadLibraryEx, LoadModule, SetDllDirectory),

Windows::Process (CreateProcess, CreateRemoteThread, CreateThread, ExitProcess, GetCommandLine, GetCurrentProcess, GetCurrentProcessId, GetEnvironmentStrings, GetEnvironmentVariable, GetExitCodeProcess, GetPriorityClass, GetProcessHandleCount, GetProcessId, GetProcessTimes, GetStartupInfo, OpenProcess, SetEnvironmentVariable, Sleep, SleepEx, TerminateProcess, WaitForInputIdle),

Windows::Synchronize (CreateEvent, CreateMutex, CreateSemaphore, GetOverlappedResult, MsgWaitForMultipleObjects, MsgWaitForMultipleObjectsEx, OpenEvent, OpenMutex, OpenSemaphore, ReleaseMutex, ReleaseSemaphore, ResetEvent, SetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx),

Windows::Window (GetClientRect, GetForegroundWindow, GetWindowRect)

Константы

PRIO_PGRP, PRIO_PROCESS, PRIO_USER, ProcessInfo, RLIMIT_AS, RLIMIT_CORE, RLIMIT_CPU, RLIMIT_DATA, RLIMIT_FSIZE, RLIMIT_MEMLOCK, RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS, RLIMIT_SBSIZE, RLIMIT_STACK, RLIM_INFINITY, RLIM_SAVED_CUR, RLIM_SAVED_MAX, WIN32_PROCESS_VERSION, WNOHANG, WUNTRACED

Методы класса

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

Методы объекта

create, fork, kill, wait2, waitpid2, waitpid, wait

Process::abortПравить


 abort
 Kernel::abort
 Process::abort

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

Process::detachПравить


 Process.detach(pid)   => thread

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. detach only checks the status periodically (currently once each second). 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)

Process::egidПравить


 Process.egid          => fixnum
 Process::GID.eid      => fixnum
 Process::Sys.geteid   => fixnum

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

  Process.egid   #=> 500

Process::egid=Править


 Process.egid = fixnum   => fixnum

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

Process::euidПравить


 Process.euid           => fixnum
 Process::UID.eid       => fixnum
 Process::Sys.geteuid   => fixnum

Returns the effective user ID for this process.

  Process.euid   #=> 501

Process::euid=Править


 Process.euid= integer

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

Process::exitПравить


 exit(integer=0)
 Kernel::exit(integer=0)
 Process::exit(integer=0)

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

Process::exit!Править


 Process.exit!(fixnum=-1)

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

  Process.exit!(0)

Process::forkПравить


 Kernel.fork  [{ block }]   => fixnum or nil
 Process.fork [{ block }]   => fixnum or nil

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.

Process::getpgidПравить


 Process.getpgid(pid)   => integer

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

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

Process::getpriorityПравить


 Process.getpriority(kind, integer)   => fixnum

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

Process::getrlimitПравить


 Process.getrlimit(resource)   => [cur_limit, max_limit]

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: such as Process::RLIMIT_CORE, Process::RLIMIT_CPU, etc. 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.

Process::gidПравить


 Process.gid           => fixnum
 Process::GID.rid      => fixnum
 Process::Sys.getgid   => fixnum

Returns the (real) group ID for this process.

  Process.gid   #=> 500

Process::gid=Править


 Process.gid= fixnum   => fixnum

Sets the group ID for this process.

Process::groupsПравить


 Process.groups   => array

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

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

Process::groups=Править


 Process.groups= array   => array

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]

Process::initgroupsПравить


 Process.initgroups(username, gid)   => array

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]

Process::killПравить


 Process.kill(signal, pid, ...)    => fixnum

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!

Process::maxgroupsПравить


 Process.maxgroups   => fixnum

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

  Process.maxgroups   #=> 32

Process::maxgroups=Править


 Process.maxgroups= fixnum   => fixnum

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

Process::pidПравить


 Process.pid   => fixnum

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

  Process.pid   #=> 27415

Process::ppidПравить


 Process.ppid   => fixnum

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

Process::setpgidПравить


 Process.setpgid(pid, integer)   => 0

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

Process::setpgrpПравить


 Process.setpgrp   => 0

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

Process::setpriorityПравить


 Process.setpriority(kind, integer, priority)   => 0

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

Process::setrlimitПравить


 Process.setrlimit(resource, cur_limit, max_limit)        => nil
 Process.setrlimit(resource, cur_limit)                   => nil

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. The list of resources are OS dependent. Ruby may support following resources.

Process::RLIMIT_CORE
core size (bytes) (SUSv3)
Process::RLIMIT_CPU
CPU time (seconds) (SUSv3)
Process::RLIMIT_DATA
data segment (bytes) (SUSv3)
Process::RLIMIT_FSIZE
file size (bytes) (SUSv3)
Process::RLIMIT_NOFILE
file descriptors (number) (SUSv3)
Process::RLIMIT_STACK
stack size (bytes) (SUSv3)
Process::RLIMIT_AS
total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD but 4.4BSD-Lite)
Process::RLIMIT_MEMLOCK
total size for mlock(2) (bytes) (4.4BSD, GNU/Linux)
Process::RLIMIT_NPROC
number of processes for the user (number) (4.4BSD, GNU/Linux)
Process::RLIMIT_RSS
resident memory size (bytes) (4.2BSD, GNU/Linux)
Process::RLIMIT_SBSIZE
all socket buffers (bytes) (NetBSD, FreeBSD)

Other Process::RLIMIT_??? constants may be defined.

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

Process::setsidПравить


 Process.setsid   => fixnum

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

Process::timesПравить


 Process.times   => aStructTms

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]

Process::uidПравить


 Process.uid           => fixnum
 Process::UID.rid      => fixnum
 Process::Sys.getuid   => fixnum

Returns the (real) user ID of this process.

  Process.uid   #=> 501

Process::uid=Править


 Process.uid= integer   => numeric

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

Process::waitПравить


 Process.wait()                     => fixnum
 Process.wait(pid=-1, flags=0)      => fixnum
 Process.waitpid(pid=-1, flags=0)   => fixnum

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 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                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, Process::WNOHANG)   #=> nil
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, 0)                  #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003

Process::wait2Править


 Process.wait2(pid=-1, flags=0)      => [pid, status]
 Process.waitpid2(pid=-1, flags=0)   => [pid, status]

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

Process::waitallПравить


 Process.waitall   => [ [pid1,status1], ...]

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)>]]

Process::waitpidПравить


 Process.wait()                     => fixnum
 Process.wait(pid=-1, flags=0)      => fixnum
 Process.waitpid(pid=-1, flags=0)   => fixnum

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 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                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, Process::WNOHANG)   #=> nil
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, 0)                  #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003

Process::waitpid2Править


 Process.wait2(pid=-1, flags=0)      => [pid, status]
 Process.waitpid2(pid=-1, flags=0)   => [pid, status]

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

Process#createПравить


 create(args)

Process.create(key => value, ...) => ProcessInfo This is a wrapper for the CreateProcess() function. It executes a process, returning a ProcessInfo struct. It accepts a hash as an argument. There are six primary keys:

  • app_name (mandatory)
  • inherit (default: false)
  • process_inherit (default: false)
  • thread_inherit (default: false)
  • creation_flags (default: 0)
  • cwd (default: Dir.pwd)
  • startup_info (default: nil)
  • environment (default: nil)

Of these, the 'app_name' must be specified or an error is raised. The startup_info key takes a hash. Its keys are attributes that are part of the StartupInfo struct, and are generally only meaningful for GUI or console processes. See the documentation on CreateProcess() and the StartupInfo struct on MSDN for more information.

  • desktop
  • title
  • x
  • y
  • x_size
  • y_size
  • x_count_chars
  • y_count_chars
  • fill_attribute
  • sw_flags
  • startf_flags

The relevant constants for 'creation_flags', 'sw_flags' and 'startf_flags' are included in the Windows::Process, Windows::Console and Windows::Window modules. These come with the windows-pr package, a prerequisite of this package. The ProcessInfo struct contains the following members:

  • process_handle - The handle to the newly created process
  • thread_handle - The handle to the primary thread of the newly created
  • process.
  • process_id - Process ID.
  • thread_id - Thread ID.

Process#forkПравить


 fork() {|| ...}

Creates the equivalent of a subshell via the CreateProcess() function. This behaves in a manner that is similar, but not identical to, the Kernel.fork method for Unix.

Process#killПравить


 kill(signal, *pids)

Sends the given signal to an array of process id's. The signal may be any value from 0 to 9, or the special strings 'SIGINT' (or 'INT'), 'SIGBRK' (or 'BRK') and 'SIGKILL' (or 'KILL'). An array of successfully killed pids is returned. Signal 0 merely tests if the process is running without killing it. Signal 2 sends a CTRL_C_EVENT to the process. Signal 3 sends a CTRL_BRK_EVENT to the process. Signal 9 kills the process in a harsh manner. Signals 1 and 4-8 kill the process in a nice manner. SIGINT/INT corresponds to signal 2 SIGBRK/BRK corresponds to signal 3 SIGKILL/KILL corresponds to signal 9 Signals 2 and 3 only affect console processes, and then only if the process was created with the CREATE_NEW_PROCESS_GROUP flag.

Process#waitПравить


 wait()

Waits for any child process to exit and returns the process id of that child. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#wait2Править


 wait2()

Waits for any child process to exit and returns an array containing the process id and the exit status of that child. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#waitpidПравить


 waitpid(pid)

Waits for the given child process to exit and returns that pid. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#waitpid2Править


 waitpid2(pid)

Waits for the given child process to exit and returns an array containing the process id and the exit status. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.