All Projects → timcharper → background_process

timcharper / background_process

Licence: MIT license
The ultimate library for UNIX process control

Programming Languages

ruby
36898 projects - #4 most used programming language

Background Process

This is like popen4, but provides several convenience methods for interacting
with the process. It only works on POSIX and Ruby implementations that support
fork and native POSIX I/O streams.

Click here for Complete Documentation

Example:

process = BackgroundProcess.run("sh -c 'sleep 1; exit 1'")
process.running? # => true
process.wait # => #<Process::Status: pid=34774,exited(1)>
process.running? #=> false
process.exitstatus # => 1
process = BackgroundProcess.run("sh", "-c", "sleep 1; exit 1")
process.kill("KILL") # => true
process.running? # => false
process.exitstatus # => nil
process = BackgroundProcess.run("sh -c '
  echo Service Starting
  sleep 2
  echo Service Started 1>&2
'")
if process.detect(:stderr, 10) { |line| line.include?("Service Started") }
  puts "Service was started!"
else
  puts "Service failed to start!"
end
process.kill

Common signal names

Name id
HUP 1
INT 2
QUIT 3
ABRT 6
KILL 9
ALRM 14
TERM 15
USR1 30
USR2 31

A word about buffered output

Some processes (like Ruby) buffer their output if they detect that they aren’t
attached to a tty. This means that unless the program explicitly calls
STDOUT.flush, much of the output won’t be available for reading until the
buffer is full, forcing it to be flushed.

You can force the output of a ruby script to be unbuffered by using a wrapper
like the following:

  BackgroundProcess.run %(ruby -e 'STDERR.sync, STDOUT.sync = true, true; $0="./server.rb"; load "server.rb"')

If no such workaround is available, this gem provides PTYBackgroundProcess
which will wrap the command any pseudo-terminal interface. This has the
advantage of forcing many programs to not buffer their output, but at a
disadvantage too (you can’t get the exit status of the process, you lose any
output that hasn’t been read yet when the process exits, and stderr gets
merged into stdout). It seems there should be ways to work around these
limitations, but I wasn’t able to figure out an way to do it (without
resorting to C code at least). Given your circumstances, this may fit your
needs and be a viable solution to you.

Please see the documentation for BackgroundProcess.run and
PTYBackgroundProcess.run for further information.

Author

Tim Harper, on behalf of Lead Media Partners

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].