2

I run this script:

t = fork do
  Signal.trap "INT" do
    puts "child"
    exit
  end

  sleep 10
end


Signal.trap "INT" do
  puts "parent"
  Process.kill "INT", t
  Process.waitpid t  
  exit
end

Process.waitpid t

When I do CTRL+C, I get

$ ruby sigtest.rb 
^Cchild 
parent

You can see that "INT" passed to every process and Process.kill "INT", t try to kill process which already died. Is there way to do so that user INT signal will be passed only to the parent? And output will be:

$ ruby sigtest.rb 
^Cparent
child

Solution

Rules:

  • When you press ctrl+c, SIGINT is passed to whole process group.
  • When you fork new process, signal handlers are not passed to new process

So if you want to control child process signals manually, you have to change GID of the process.

See

  def system cmd
    pid = fork do
     exec cmd, {:pgroup => true}
    end

    Process.wait pid
    $?.success?
  end

  def ` cmd # `make syntax highlight happy

    readme, writeme = IO.pipe
    pid = fork do
      $stdout.reopen writeme
      readme.close
      exec cmd, {:pgroup => true}
    end

    writeme.close
    data = readme.read

    Process.wait pid

    data
  end

1 Answer 1

0

You could always have the child ignore the INT signal.

2
  • I want different thing. I corrected the script to be more understandable Aug 3, 2011 at 15:23
  • Ignore the INT and send the child a different signal to terminate, like USR1 or HUP, whatever seems like a good fit. Add another signal handler to the child to intercept this and exit properly.
    – tadman
    Aug 3, 2011 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.