Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
The ultimate library for UNIX process control
Ruby
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gemtest
.gitignore
Gemfile
Gemfile.lock
MIT-LICENSE
README.textile
Rakefile
background_process.gemspec

README.textile

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

Something went wrong with that request. Please try again.