Class: Cod::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/cod/process.rb

Overview

A subprocess that is being run in server mode (think git-server). Use Cod.process to obtain an instance of this. You can then call #channel to obtain a Cod channel to communicate with the $stdio server you’ve spawned.

Examples:

List the files in a directory

process = Cod.process('ls', Cod::LineSerializer.new)
process.wait
loop do
  # Will list all entries of the current dir in turn, already chomped.
  msg = process.get rescue nil
  break unless msg
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, serializer = nil) ⇒ Process

Constructs a process object and runs the command.

See Also:

  • Cod#process


24
25
26
27
28
# File 'lib/cod/process.rb', line 24

def initialize(command, serializer=nil)
  @serializer = serializer || SimpleSerializer.new

  run(command)
end

Instance Attribute Details

#pidNumber (readonly)

The pid of the process that was spawned.

Returns:

  • (Number)


19
20
21
# File 'lib/cod/process.rb', line 19

def pid
  @pid
end

Instance Method Details

#channelCod::Pipe

Returns the cod channel associated with this process. The channel will have the process’ standard output bound to its #get (input), and the process’ standard input will be bound to #put (output).

Note that when the process exits and all communication has been read from the channel, it will probably raise a Cod::ConnectionLost error.

Examples:

process = Cod.process('uname', LineSerializer.new)
process.channel.get # => {Darwin,Linux,...}

Returns:



57
58
59
# File 'lib/cod/process.rb', line 57

def channel
  @pipe
end

#killvoid

This method returns an undefined value.

Stops the process unilaterally.



65
66
67
68
# File 'lib/cod/process.rb', line 65

def kill
  terminate
  ::Process.kill :TERM, @pid
end

#run(command) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cod/process.rb', line 31

def run(command)
  @pipe = Cod.bidir(@serializer)
  
  @pid = ::Process.spawn(command, 
    :in => @pipe.other, 
    :out => @pipe.other)
    
  # Close the end we just dedicated to the process we've spawned. 
  # As a consequence, when the process exists, we'll get a read error
  # on our side of the pipe (@pipe.socket, #put, #get)
  @pipe.other.close
end

#terminatevoid

This method returns an undefined value.

Asks the process to terminate by closing its stanard input. This normally closes down the process, but no guarantees are made.



75
76
77
# File 'lib/cod/process.rb', line 75

def terminate
  @pipe.socket.close_write
end

#waitNumber?

Waits for the process to terminate and returns its exit value. May return nil, in which case someone else already reaped the process.

Returns:

  • (Number, nil)


84
85
86
87
# File 'lib/cod/process.rb', line 84

def wait
  ::Process.wait(@pid)
rescue Errno::ECHILD
end