在分叉进程中停止脚本

时间:2012-03-28 13:18:30

标签: ruby

我有

backupCommand = "rsync #{rsyncOptions} #{directory} #{backupSSH}:#{@backupPath}"
pid = fork {   
  system backupCommand
  Kernel.trap('INT') {
    Kernel.exit
  }   
}   
Process.detach(pid)

我想要发生的是,如果脚本运行并且我想要停止它,则ctrl-c应该终止脚本并且所有进程都会分叉。

1 个答案:

答案 0 :(得分:0)

正如@Victor Moroz指出的那样,分离的进程无法从键盘接收^ C.如果您的前台仍在运行其他工作,它可以记住分离的pid并在收到SIGINT时向它发送一个kill信号。例如:

#!/usr/bin/env ruby                                             

got_sigint = false
backupCommand = "/usr/bin/env sleep 5"
pid = spawn backupCommand

Process.detach(pid)
puts "detached #{pid}"

Kernel.trap('INT') {
  got_sigint = true
}

until got_sigint
  system "ps -p #{pid}"
  sleep 1
end

if got_sigint
  begin Process.kill('KILL',pid) rescue Errno::ESRCH end
  sleep 1
  system "ps -p #{pid}"
end

如果我运行此等待> 5秒,你看到产生的进程自然退出:

detached 8565
  PID TTY          TIME CMD
 8565 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
 8565 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
 8565 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
 8565 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
 8565 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
  PID TTY          TIME CMD
^C  PID TTY          TIME CMD

如果我再次运行并在5秒之前发送^ C,前台进程将捕获sigint并杀死背景:

detached 8588
  PID TTY          TIME CMD
 8588 pts/1    00:00:00 sleep
  PID TTY          TIME CMD
 8588 pts/1    00:00:00 sleep
^C  PID TTY          TIME CMD