Search code examples
rubyubuntubackground-process

How to run a ruby shell script that shows some information, then asks for input and goes background?


I have a ruby shell script that I want to run on background. However, before going to background I need to ask for an user input.

Is it possible? How can it be achieved?

Thanks in advance!


Solution

  • Here's a simple example:

    def do_stuff(input)
      puts "Input received: #{input}"
      sleep 10
    end
    
    print "Enter input value: "
    input = gets
    pid = fork { do_stuff(input) }
    puts "test.rb started, pid: #{pid}"
    Process.detach pid
    

    Note the use of fork to start a new process, and detach to allow the subprocess to continue running while the main process exits.

    Some platforms (Windows) don't support fork.