DEV: support USR2 to restart unicorn in dev mode

DEV: support USR2 to restart unicorn in dev mode

In dev mode sending USR2 to the unicorn master supervisor process will restart unicorn.

This allows a simple script like this to restart unicorn in dev:

#!/usr/bin/env bash

kill -s USR2 `ps aux | grep ruby\ bin\/unicorn | grep -v grep | awk '{print $2}'`
diff --git a/bin/unicorn b/bin/unicorn
index cff2163..01b9002 100755
--- a/bin/unicorn
+++ b/bin/unicorn
@@ -8,11 +8,15 @@ ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile",
 require 'rubygems'
 require 'bundler/setup'
 
+dev_mode = false
+
 # in development do some fussing around, to automate config
 if !ARGV.include?("-E") &&
     !ARGV.include?("--env") &&
     (ENV["RAILS_ENV"] == "development" || !ENV["RAILS_ENV"])
 
+  dev_mode = true
+
   ARGV.push("-N")
   if !ARGV.include?("-c") && !ARGV.include?("--config-file")
     ARGV.push("-c")
@@ -46,4 +50,37 @@ if ARGV.include?("--help")
   exit
 end
 
-load Gem.bin_path('unicorn', 'unicorn')
+# this dev_mode hackery enables, the following script to be used to restart unicorn:
+#
+# #!/usr/bin/env bash
+# kill -s USR2 `ps aux | grep ruby\ bin\/unicorn | grep -v grep | awk '{print $2}'`
+#
+# This is handy if you want to bind a key to restarting unicorn in dev
+
+if dev_mode
+  restart = true
+  while restart
+    restart = false
+    pid = fork do
+      load Gem.bin_path('unicorn', 'unicorn')
+    end
+    done = false
+
+    Signal.trap('INT') do
+      # wait for parent to be done
+    end
+
+    Signal.trap('USR2') do
+      Process.kill('QUIT', pid)
+      puts "RESTARTING UNICORN"
+      restart = true
+    end
+
+    while !done
+      sleep 1
+      done = Process.waitpid(pid, Process::WNOHANG)
+    end
+  end
+else
+  load Gem.bin_path('unicorn', 'unicorn')
+end

GitHub sha: fb8d1f35

1 Like