Module: Process

Extended by:
Windows::Console, Windows::Error, Windows::Handle, Windows::Library, Windows::MSVCRT::String, Windows::Process, Windows::Security, Windows::Synchronize, Windows::Thread, Windows::ToolHelper, Windows::Unicode
Includes:
Windows::Console, Windows::Error, Windows::Handle, Windows::Library, Windows::MSVCRT::String, Windows::Process, Windows::Security, Windows::Synchronize, Windows::Thread, Windows::ToolHelper, Windows::Unicode, Windows::Window
Defined in:
lib/win32/process.rb

Defined Under Namespace

Classes: Error, ProcessInfo

Constant Summary collapse

WIN32_PROCESS_VERSION =

The version of the win32-process library

'0.6.6'
PRIO_PROCESS =

Defined for interface compatibility, but not used

0
PRIO_PGRP =
1
PRIO_USER =
2
RLIMIT_CPU =

PerProcessUserTimeLimit

0
RLIMIT_FSIZE =

Hard coded at 4TB - 64K (assumes NTFS)

1
RLIMIT_AS =

ProcessMemoryLimit

5
RLIMIT_RSS =

ProcessMemoryLimit

5
RLIMIT_VMEM =

ProcessMemoryLimit

5

Class Method Summary collapse

Class Method Details

.create(args) ⇒ Object

  • desktop

  • title

  • x

  • y

  • x_size

  • y_size

  • x_count_chars

  • y_count_chars

  • fill_attribute

  • sw_flags

  • startf_flags

  • stdin

  • stdout

  • stderr

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 library, a prerequisite of this library. Note that the ‘stdin’, ‘stdout’ and ‘stderr’ options can be either Ruby IO objects or file descriptors (i.e. a fileno). However, StringIO objects are not currently supported.

If ‘stdin’, ‘stdout’ or ‘stderr’ are specified, then the inherit value is automatically set to true and the Process::STARTF_USESTDHANDLES flag is automatically OR’d to the startf_flags value.

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 process.

  • process_id - Process ID.

  • thread_id - Thread ID.

If the ‘close_handles’ option is set to true (the default) then the process_handle and the thread_handle are automatically closed for you before the ProcessInfo struct is returned.

If the ‘with_logon’ option is set, then the process runs the specified executable file in the security context of the specified credentials.



708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
# File 'lib/win32/process.rb', line 708

def create(args)
  unless args.kind_of?(Hash)
    raise TypeError, 'Expecting hash-style keyword arguments'
  end

  valid_keys = %w/
    app_name command_line inherit creation_flags cwd environment
    startup_info thread_inherit process_inherit close_handles with_logon
    domain password
  /

  valid_si_keys = %/
    startf_flags desktop title x y x_size y_size x_count_chars
    y_count_chars fill_attribute sw_flags stdin stdout stderr
  /

  # Set default values
  hash = {
    'app_name'       => nil,
    'creation_flags' => 0,
    'close_handles'  => true
  }

  # Validate the keys, and convert symbols and case to lowercase strings.
  args.each{ |key, val|
    key = key.to_s.downcase
    unless valid_keys.include?(key)
      raise ArgumentError, "invalid key '#{key}'"
    end
    hash[key] = val
  }

  si_hash = {}

  # If the startup_info key is present, validate its subkeys
  if hash['startup_info']
    hash['startup_info'].each{ |key, val|
      key = key.to_s.downcase
      unless valid_si_keys.include?(key)
        raise ArgumentError, "invalid startup_info key '#{key}'"
      end
      si_hash[key] = val
    }
  end

  # The +command_line+ key is mandatory unless the +app_name+ key
  # is specified.
  unless hash['command_line']
    if hash['app_name']
      hash['command_line'] = hash['app_name']
      hash['app_name'] = nil
    else
      raise ArgumentError, 'command_line or app_name must be specified'
    end
  end

  # The environment string should be passed as a string of ';' separated
  # paths.
  if hash['environment']
    env = hash['environment'].split(File::PATH_SEPARATOR) << 0.chr
    if hash['with_logon']
      env = env.map{ |e| multi_to_wide(e) }
      env = [env.join("\0\0")].pack('p*').unpack('L').first
    else
      env = [env.join("\0")].pack('p*').unpack('L').first
    end
  else
    env = nil
  end

  startinfo = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  startinfo = startinfo.pack('LLLLLLLLLLLLSSLLLL')
  procinfo  = [0,0,0,0].pack('LLLL')

  # Process SECURITY_ATTRIBUTE structure
  process_security = 0
  if hash['process_inherit']
    process_security = [0,0,0].pack('LLL')
    process_security[0,4] = [12].pack('L') # sizeof(SECURITY_ATTRIBUTE)
    process_security[8,4] = [1].pack('L')  # TRUE
  end

  # Thread SECURITY_ATTRIBUTE structure
  thread_security = 0
  if hash['thread_inherit']
    thread_security = [0,0,0].pack('LLL')
    thread_security[0,4] = [12].pack('L') # sizeof(SECURITY_ATTRIBUTE)
    thread_security[8,4] = [1].pack('L')  # TRUE
  end

  # Automatically handle stdin, stdout and stderr as either IO objects
  # or file descriptors.  This won't work for StringIO, however.
  ['stdin', 'stdout', 'stderr'].each{ |io|
    if si_hash[io]
      if si_hash[io].respond_to?(:fileno)
        handle = get_osfhandle(si_hash[io].fileno)
      else
        handle = get_osfhandle(si_hash[io])
      end

      if handle == INVALID_HANDLE_VALUE
        raise Error, get_last_error
      end

      # Most implementations of Ruby on Windows create inheritable
      # handles by default, but some do not. RF bug #26988.
      bool = SetHandleInformation(
        handle,
        HANDLE_FLAG_INHERIT,
        HANDLE_FLAG_INHERIT
      )

      raise Error, get_last_error unless bool

      si_hash[io] = handle
      si_hash['startf_flags'] ||= 0
      si_hash['startf_flags'] |= STARTF_USESTDHANDLES
      hash['inherit'] = true
    end
  }

  # The bytes not covered here are reserved (null)
  unless si_hash.empty?
    startinfo[0,4]  = [startinfo.size].pack('L')
    startinfo[8,4]  = [si_hash['desktop']].pack('p*') if si_hash['desktop']
    startinfo[12,4] = [si_hash['title']].pack('p*') if si_hash['title']
    startinfo[16,4] = [si_hash['x']].pack('L') if si_hash['x']
    startinfo[20,4] = [si_hash['y']].pack('L') if si_hash['y']
    startinfo[24,4] = [si_hash['x_size']].pack('L') if si_hash['x_size']
    startinfo[28,4] = [si_hash['y_size']].pack('L') if si_hash['y_size']
    startinfo[32,4] = [si_hash['x_count_chars']].pack('L') if si_hash['x_count_chars']
    startinfo[36,4] = [si_hash['y_count_chars']].pack('L') if si_hash['y_count_chars']
    startinfo[40,4] = [si_hash['fill_attribute']].pack('L') if si_hash['fill_attribute']
    startinfo[44,4] = [si_hash['startf_flags']].pack('L') if si_hash['startf_flags']
    startinfo[48,2] = [si_hash['sw_flags']].pack('S') if si_hash['sw_flags']
    startinfo[56,4] = [si_hash['stdin']].pack('L') if si_hash['stdin']
    startinfo[60,4] = [si_hash['stdout']].pack('L') if si_hash['stdout']
    startinfo[64,4] = [si_hash['stderr']].pack('L') if si_hash['stderr']
  end

  if hash['with_logon']
    logon  = multi_to_wide(hash['with_logon'])
    domain = multi_to_wide(hash['domain'])
    app    = hash['app_name'].nil? ? nil : multi_to_wide(hash['app_name'])
    cmd    = hash['command_line'].nil? ? nil : multi_to_wide(hash['command_line'])
    cwd    = multi_to_wide(hash['cwd'])
    passwd = multi_to_wide(hash['password'])

    hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT

    bool = CreateProcessWithLogonW(
      logon,                  # User
      domain,                 # Domain
      passwd,                 # Password
      LOGON_WITH_PROFILE,     # Logon flags
      app,                    # App name
      cmd,                    # Command line
      hash['creation_flags'], # Creation flags
      env,                    # Environment
      cwd,                    # Working directory
      startinfo,              # Startup Info
      procinfo                # Process Info
    )
  else
    bool = CreateProcess(
      hash['app_name'],       # App name
      hash['command_line'],   # Command line
      process_security,       # Process attributes
      thread_security,        # Thread attributes
      hash['inherit'],        # Inherit handles?
      hash['creation_flags'], # Creation flags
      env,                    # Environment
      hash['cwd'],            # Working directory
      startinfo,              # Startup Info
      procinfo                # Process Info
    )
  end

  # TODO: Close stdin, stdout and stderr handles in the si_hash unless
  # they're pointing to one of the standard handles already. [Maybe]
  unless bool
    raise Error, "CreateProcess() failed: " + get_last_error
  end

  # Automatically close the process and thread handles in the
  # PROCESS_INFORMATION struct unless explicitly told not to.
  if hash['close_handles']
    CloseHandle(procinfo[0,4].unpack('L').first)
    CloseHandle(procinfo[4,4].unpack('L').first)
  end

  ProcessInfo.new(
    procinfo[0,4].unpack('L').first, # hProcess
    procinfo[4,4].unpack('L').first, # hThread
    procinfo[8,4].unpack('L').first, # hProcessId
    procinfo[12,4].unpack('L').first # hThreadId
  )
end

.forkObject

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. Unlike the Unix fork, this method starts from the top of the script rather than the point of the call.

WARNING: This implementation should be considered experimental. It is not recommended for production use.



1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
# File 'lib/win32/process.rb', line 1086

def fork
  last_arg = ARGV.last

  # Look for the 'child#xxx' tag
  if last_arg =~ /child#\d+/
    @i += 1
    num = last_arg.split('#').last.to_i
    if num == @i
      if block_given?
        status = 0
        begin
          yield
        rescue Exception
          status = -1 # Any non-zero result is failure
        ensure
          return status
        end
      end
      return nil
    else
      return false
    end
  end

  # Tag the command with the word 'child#xxx' to distinguish it
  # from the calling process.
  cmd = 'ruby -I "' + $LOAD_PATH.join(File::PATH_SEPARATOR) << '" "'
  cmd << File.expand_path($PROGRAM_NAME) << '" ' << ARGV.join(' ')
  cmd << ' child#' << @child_pids.length.to_s

  startinfo = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  startinfo = startinfo.pack('LLLLLLLLLLLLSSLLLL')
  procinfo  = [0,0,0,0].pack('LLLL')

  rv = CreateProcess(nil, cmd, 0, 0, 1, 0, 0, 0, startinfo, procinfo)

  if rv == 0
    raise Error, get_last_error
  end

  pid = procinfo[8,4].unpack('L').first
  @child_pids.push(pid)

  pid
end

.get_affinity(int = Process.pid) ⇒ Object

Returns the process and system affinity mask for the given pid, or the current process if no pid is provided. The return value is a two element array, with the first containing the process affinity mask, and the second containing the system affinity mask. Both are decimal values.

A process affinity mask is a bit vector indicating the processors that a process is allowed to run on. A system affinity mask is a bit vector in which each bit represents the processors that are configured into a system.

Example:

# System has 4 processors, current process is allowed to run on all
Process.get_affinity # => [[15], [15]]

# System has 4 processors, current process only allowed on 1 and 4 only
Process.get_affinity # => [[9], [15]]

If you want to convert a decimal bit vector into an array of 0’s and 1’s indicating the flag value of each processor, you can use something like this approach:

mask = Process.get_affinity.first
(0..mask).to_a.map{ |n| mask[n] }


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/win32/process.rb', line 106

def get_affinity(int = Process.pid)
  pmask = 0.chr * 4
  smask = 0.chr * 4

  if int == Process.pid
    unless GetProcessAffinityMask(GetCurrentProcess(), pmask, smask)
      raise Error, get_last_error
    end
  else
    begin
      handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0 , int)

      if handle == INVALID_HANDLE_VALUE
        raise Error, get_last_error
      end

      unless GetProcessAffinityMask(handle, pmask, smask)
        raise Error, get_last_error
      end
    ensure
      CloseHandle(handle) if handle != INVALID_HANDLE_VALUE
    end
  end

  pmask = pmask.unpack('L').first
  smask = smask.unpack('L').first

  [pmask, smask]
end

.getpriority(kind, int) ⇒ Object

Retrieves the priority class for the specified process id int. Unlike the default implementation, lower return values do not necessarily correspond to higher priority classes.

The kind parameter is ignored but required for API compatibility. You can only retrieve process information, not process group or user information, so it is effectively always Process::PRIO_PROCESS.

Possible return values are:

32 - Process::NORMAL_PRIORITY_CLASS 64 - Process::IDLE_PRIORITY_CLASS 128 - Process::HIGH_PRIORITY_CLASS 256 - Process::REALTIME_PRIORITY_CLASS 16384 - Process::BELOW_NORMAL_PRIORITY_CLASS 32768 - Process::ABOVE_NORMAL_PRIORITY_CLASS

Raises:

  • (TypeError)


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/win32/process.rb', line 332

def getpriority(kind, int)
  raise TypeError unless kind.is_a?(Integer)
  raise TypeError unless int.is_a?(Integer)

  int = Process.pid if int == 0 # Match spec

  handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0 , int)

  if handle == INVALID_HANDLE_VALUE
    raise Error, get_last_error
  end

  begin
    priority_class = GetPriorityClass(handle)

    if priority_class == 0
      raise Error, get_last_error
    end
  ensure
    CloseHandle(handle)
  end

  priority_class
end

.getrlimit(resource) ⇒ Object

Gets the resource limit of the current process. Only a limited number of flags are supported.

Process::RLIMIT_CPU Process::RLIMIT_FSIZE Process::RLIMIT_AS Process::RLIMIT_RSS Process::RLIMIT_VMEM

The Process:RLIMIT_AS, Process::RLIMIT_RSS and Process::VMEM constants all refer to the Process memory limit. The Process::RLIMIT_CPU constant refers to the per process user time limit. The Process::RLIMIT_FSIZE constant is hard coded to the maximum file size on an NTFS filesystem, approximately 4TB (or 4GB if not NTFS).

While a two element array is returned in order to comply with the spec, there is no separate hard and soft limit. The values will always be the same.

If [0,0] is returned then it means no limit has been set.

Example:

Process.getrlimit(Process::RLIMIT_VMEM) # => [0, 0]

– NOTE: Both the getrlimit and setrlimit method use an at_exit handler to close a job handle. This is necessary because simply calling it at the end of the block, while marking it for closure, would also make it unavailable even within the same process since it would no longer be associated with the job.



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/win32/process.rb', line 175

def getrlimit(resource)
  if resource == RLIMIT_FSIZE
    if get_volume_type == 'NTFS'
      return ((1024**4) * 4) - (1024 * 64) # ~4 TB
    else
      return (1024**3) * 4 # 4 GB
    end
  end

  handle = nil
  in_job = Process.job?

  # Put the current process in a job if it's not already in one
  if in_job && defined?(@job_name)
    handle = OpenJobObject(JOB_OBJECT_QUERY, true, @job_name)
    raise Error, get_last_error if handle == 0
  else
    @job_name = 'ruby_' + Process.pid.to_s
    handle = CreateJobObject(nil, @job_name)
    raise Error, get_last_error if handle == 0
  end

  begin
    unless in_job
      unless AssignProcessToJobObject(handle, GetCurrentProcess())
        raise Error, get_last_error
      end
    end

    buf = 0.chr * 112 # sizeof(struct JOBJECT_EXTENDED_LIMIT_INFORMATION)
    val = nil         # value returned at end of method

    # Set the LimitFlags member of the struct
    case resource
      when RLIMIT_CPU
        buf[16,4] = [JOB_OBJECT_LIMIT_PROCESS_TIME].pack('L')
      when RLIMIT_AS, RLIMIT_VMEM, RLIMIT_RSS
        buf[16,4] = [JOB_OBJECT_LIMIT_PROCESS_MEMORY].pack('L')
      else
        raise Error, "unsupported resource type"
    end

    bool = QueryInformationJobObject(
      handle,
      JobObjectExtendedLimitInformation,
      buf,
      buf.size,
      nil
    )

    unless bool
      raise Error, get_last_error
    end

    case resource
      when Process::RLIMIT_CPU
        val = buf[0,8].unpack('Q').first
      when RLIMIT_AS, RLIMIT_VMEM, RLIMIT_RSS
        val = buf[96,4].unpack('L').first
    end
  ensure
    at_exit{ CloseHandle(handle) if handle }
  end

  [val, val] # Return an array of two values to comply with spec
end

.job?Boolean

Returns whether or not the current process is part of a Job.

Returns:

  • (Boolean)


138
139
140
141
142
# File 'lib/win32/process.rb', line 138

def job?
  pbool = 0.chr * 4
  IsProcessInJob(GetCurrentProcess(), nil, pbool)
  pbool.unpack('L').first == 0 ? false : true
end

.kill(signal, *pids) ⇒ Object

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.



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
# File 'lib/win32/process.rb', line 539

def kill(signal, *pids)
  case signal
    when 'SIGINT', 'INT'
      signal = 2
    when 'SIGBRK', 'BRK'
      signal = 3
    when 'SIGKILL', 'KILL'
      signal = 9
    when 0..9
      # Do nothing
    else
      raise Error, "Invalid signal '#{signal}'"
  end

  killed_pids = []

  pids.each{ |pid|
    # Send the signal to the current process if the pid is zero
    if pid == 0
      pid = Process.pid
    end

    # No need for full access if the signal is zero
    if signal == 0
      access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
      handle = OpenProcess(access, 0 , pid)
    else
      handle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid)
    end

    begin
      case signal
        when 0
          if handle != 0
            killed_pids.push(pid)
          else
            # If ERROR_ACCESS_DENIED is returned, we know it's running
            if GetLastError() == ERROR_ACCESS_DENIED
              killed_pids.push(pid)
            else
              raise Error, get_last_error
            end
          end
        when 2
          if GenerateConsoleCtrlEvent(CTRL_C_EVENT, pid)
            killed_pids.push(pid)
          end
        when 3
          if GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid)
            killed_pids.push(pid)
          end
        when 9
          if TerminateProcess(handle, pid)
            killed_pids.push(pid)
            @child_pids.delete(pid)
          else
            raise Error, get_last_error
          end
        else
          if handle != 0
            thread_id = [0].pack('L')
            begin
              thread = CreateRemoteThread(
                handle,
                0,
                0,
                GetProcAddress(GetModuleHandle('kernel32'), 'ExitProcess'),
                0,
                0,
                thread_id
              )

              if thread
                WaitForSingleObject(thread, 5)
                killed_pids.push(pid)
                @child_pids.delete(pid)
              else
                raise Error, get_last_error
              end
            ensure
              CloseHandle(thread) if thread
            end
          else
            raise Error, get_last_error
          end # case

        @child_pids.delete(pid)
      end
    ensure
      CloseHandle(handle) unless handle == INVALID_HANDLE_VALUE
    end
  }

  killed_pids
end

.ppidObject

Returns the process ID of the parent of this process. – In MRI this method always returns 0.



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'lib/win32/process.rb', line 1045

def ppid
  ppid = 0

  return ppid if Process.pid == 0 # Paranoia

  handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)

  if handle == INVALID_HANDLE_VALUE
    raise Error, get_last_error
  end

  proc_entry = 0.chr * 296 # 36 + 260
  proc_entry[0, 4] = [proc_entry.size].pack('L') # Set dwSize member

  begin
    unless Process32First(handle, proc_entry)
      error = get_last_error
      raise Error, error
    end

    while Process32Next(handle, proc_entry)
      if proc_entry[8, 4].unpack('L')[0] == Process.pid
        ppid = proc_entry[24, 4].unpack('L')[0] # th32ParentProcessID
        break
      end
    end
  ensure
    CloseHandle(handle)
  end

  ppid
end

.setpriority(kind, int, int_priority) ⇒ Object

Sets the priority class for the specified process id int.

The kind parameter is ignored but present for API compatibility. You can only retrieve process information, not process group or user information, so it is effectively always Process::PRIO_PROCESS.

Possible int_priority values are:

  • Process::NORMAL_PRIORITY_CLASS

  • Process::IDLE_PRIORITY_CLASS

  • Process::HIGH_PRIORITY_CLASS

  • Process::REALTIME_PRIORITY_CLASS

  • Process::BELOW_NORMAL_PRIORITY_CLASS

  • Process::ABOVE_NORMAL_PRIORITY_CLASS

Raises:

  • (TypeError)


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/win32/process.rb', line 372

def setpriority(kind, int, int_priority)
  raise TypeError unless kind.is_a?(Integer)
  raise TypeError unless int.is_a?(Integer)
  raise TypeError unless int_priority.is_a?(Integer)

  int = Process.pid if int == 0 # Match spec

  handle = OpenProcess(PROCESS_SET_INFORMATION, 0 , int)

  if handle == INVALID_HANDLE_VALUE
    raise Error, get_last_error
  end

  begin
    unless SetPriorityClass(handle, int_priority)
      raise Error, get_last_error
    end
  ensure
    CloseHandle(handle)
  end

  return 0 # Match the spec
end

.setrlimit(resource, current_limit, max_limit = nil) ⇒ Object

Sets the resource limit of the current process. Only a limited number of flags are supported.

Process::RLIMIT_CPU Process::RLIMIT_AS Process::RLIMIT_RSS Process::RLIMIT_VMEM

The Process:RLIMIT_AS, Process::RLIMIT_RSS and Process::VMEM constants all refer to the Process memory limit. The Process::RLIMIT_CPU constant refers to the per process user time limit.

The max_limit parameter is provided for interface compatibility only. It is always set to the current_limit value.

Example:

Process.setrlimit(Process::RLIMIT_VMEM, 1024 * 4) # => nil
Process.getrlimit(Process::RLIMIT_VMEM) # => [4096, 4096]


262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/win32/process.rb', line 262

def setrlimit(resource, current_limit, max_limit = nil)
  max_limit = current_limit

  handle = nil
  in_job = Process.job?

  # Put the current process in a job if it's not already in one
  if in_job && defined? @job_name
    handle = OpenJobObject(JOB_OBJECT_SET_ATTRIBUTES, true, @job_name)
    raise Error, get_last_error if handle == 0
  else
    @job_name = 'ruby_' + Process.pid.to_s
    handle = CreateJobObject(nil, job_name)
    raise Error, get_last_error if handle == 0
  end

  begin
    unless in_job
      unless AssignProcessToJobObject(handle, GetCurrentProcess())
        raise Error, get_last_error
      end
    end

    # sizeof(struct JOBJECT_EXTENDED_LIMIT_INFORMATION)
    buf = 0.chr * 112

    # Set the LimitFlags and relevant members of the struct
    case resource
      when RLIMIT_CPU
        buf[16,4] = [JOB_OBJECT_LIMIT_PROCESS_TIME].pack('L')
        buf[0,8]  = [max_limit].pack('Q') # PerProcessUserTimeLimit
      when RLIMIT_AS, RLIMIT_VMEM, RLIMIT_RSS
        buf[16,4] = [JOB_OBJECT_LIMIT_PROCESS_MEMORY].pack('L')
        buf[96,4] = [max_limit].pack('L') # ProcessMemoryLimit
      else
        raise Error, "unsupported resource type"
    end

    bool = SetInformationJobObject(
      handle,
      JobObjectExtendedLimitInformation,
      buf,
      buf.size
    )

    unless bool
      raise Error, get_last_error
    end
  ensure
    at_exit{ CloseHandle(handle) if handle }
  end
end

.uid(sid = false) ⇒ Object

Returns the uid of the current process. Specifically, it returns the RID of the SID associated with the owner of the process.

If sid is set to true, then a binary sid is returned. Otherwise, a numeric id is returned (the default). – The Process.uid method in core Ruby always returns 0 on MS Windows.

Raises:

  • (TypeError)


404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/win32/process.rb', line 404

def uid(sid = false)
  token = 0.chr * 4

  raise TypeError unless sid.is_a?(TrueClass) || sid.is_a?(FalseClass)

  unless OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, token)
    raise Error, get_last_error
  end

  token   = token.unpack('V')[0]
  rlength = 0.chr * 4
  tuser   = 0.chr * 512

  bool = GetTokenInformation(
    token,
    TokenUser,
    tuser,
    tuser.size,
    rlength
  )

  unless bool
    raise Error, get_last_error
  end

  lsid = tuser[8, (rlength.unpack('L').first - 8)]

  if sid
    lsid
  else
    sid_addr = [lsid].pack('p*').unpack('L')[0]
    sid_buf  = 0.chr * 80
    sid_ptr  = 0.chr * 4

    unless ConvertSidToStringSid(sid_addr, sid_ptr)
      raise Error, get_last_error
    end

    strcpy(sid_buf, sid_ptr.unpack('L')[0])
    sid_buf.strip.split('-').last.to_i
  end
end

.wait(pid = -1,, flags = nil) ⇒ Object

Waits for any child process to exit and returns the process id of that child. If a pid is provided that is greater than or equal to 0, then it is the equivalent of calling Process.waitpid.

The flags argument is ignored at the moment. It is provided strictly for interface compatibility.

Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release. – The GetProcessId() function is not defined in Windows 2000 or earlier so we have to do some extra work for those platforms.



920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
# File 'lib/win32/process.rb', line 920

def wait(pid = -1, flags = nil)
  if pid && pid >= 0
    pid, status = waitpid(pid, flags)
    return pid
  end

  handles = []

  # Windows 2000 or earlier
  unless defined? GetProcessId
    pids = []
  end

  @child_pids.each_with_index{ |lpid, i|
    handles[i] = OpenProcess(PROCESS_ALL_ACCESS, 0, lpid)

    if handles[i] == INVALID_HANDLE_VALUE
      err = "unable to get HANDLE on process associated with pid #{lpid}"
      raise Error, err
    end

    unless defined? GetProcessId
      pids[i] = lpid
    end
  }

  wait = WaitForMultipleObjects(
    handles.size,
    handles.pack('L*'),
    0,
    INFINITE
  )

  if wait >= WAIT_OBJECT_0 && wait <= WAIT_OBJECT_0 + @child_pids.size - 1
    index = wait - WAIT_OBJECT_0
    handle = handles[index]

    if defined? GetProcessId
      pid = GetProcessId(handle)
    else
      pid = pids[index]
    end

    @child_pids.delete(pid)
    handles.each{ |h| CloseHandle(h) }
    return pid
  end

  nil
end

.wait2(pid = -1,, flags = nil) ⇒ Object

Waits for any child process to exit and returns an array containing the process id and the exit status of that child.

The flags argument is ignored at the moment. It is provided strictly for interface compatibility.

Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release. – The GetProcessId() function is not defined in Windows 2000 or earlier so we have to do some extra work for those platforms.



983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
# File 'lib/win32/process.rb', line 983

def wait2(pid = -1, flags = nil)
  if pid && pid >= 0
    pid, status = waitpid2(pid, flags)
    return pid
  end

  handles = []

  # Windows 2000 or earlier
  unless defined? GetProcessId
    pids = []
  end

  @child_pids.each_with_index{ |lpid, i|
    handles[i] = OpenProcess(PROCESS_ALL_ACCESS, 0, lpid)

    if handles[i] == INVALID_HANDLE_VALUE
      err = "unable to get HANDLE on process associated with pid #{lpid}"
      raise Error, err
    end

    unless defined? GetProcessId
      pids[i] = lpid
    end
  }

  wait = WaitForMultipleObjects(
    handles.size,
    handles.pack('L*'),
    0,
    INFINITE
  )

  if wait >= WAIT_OBJECT_0 && wait <= WAIT_OBJECT_0 + @child_pids.size - 1
    index = wait - WAIT_OBJECT_0
    handle = handles[index]

    if defined? GetProcessId
      pid = GetProcessId(handle)
    else
      pid = pids[index]
    end

    exit_code = [0].pack('l')

    unless GetExitCodeProcess(handle, exit_code)
      raise get_last_error
    end

    @child_pids.delete(pid)

    handles.each{ |h| CloseHandle(h) }
    return [pid, exit_code.unpack('l').first]
  end

  nil
end

.waitpid(pid, flags = nil) ⇒ Object

Waits for the given child process to exit and returns that pid.

The flags argument is ignored at the moment. It is provided strictly for interface compatibility.

Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/win32/process.rb', line 455

def waitpid(pid, flags = nil)
  exit_code = [0].pack('L')
  handle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid)

  if handle == INVALID_HANDLE_VALUE
    raise Error, get_last_error
  end

  # TODO: update the $? global variable (if/when possible)
  status = WaitForSingleObject(handle, INFINITE)

  begin
    unless GetExitCodeProcess(handle, exit_code)
      raise Error, get_last_error
    end
  ensure
    CloseHandle(handle)
  end

  @child_pids.delete(pid)

  # TODO: update the $? global variable (if/when possible)
  exit_code = exit_code.unpack('L').first

  pid
end

.waitpid2(pid, flags = nil) ⇒ Object

Waits for the given child process to exit and returns an array containing the process id and the exit status.

The flags argument is ignored at the moment. It is provided strictly for interface compatibility.

Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release if/when possible. – Ruby does not provide a way to hook into $? so there’s no way for us to set it.



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/win32/process.rb', line 494

def waitpid2(pid, flags = nil)
  exit_code = [0].pack('L')
  handle    = OpenProcess(PROCESS_ALL_ACCESS, 0, pid)

  if handle == INVALID_HANDLE_VALUE
    raise Error, get_last_error
  end

  # TODO: update the $? global variable (if/when possible)
  status = WaitForSingleObject(handle, INFINITE)

  begin
    unless GetExitCodeProcess(handle, exit_code)
      raise Error, get_last_error
    end
  ensure
    CloseHandle(handle)
  end

  @child_pids.delete(pid)

  # TODO: update the $? global variable (if/when possible)
  exit_code = exit_code.unpack('L').first

  [pid, exit_code]
end