1 # -*- encoding: binary -*-
5 require 'unicorn/socket_helper'
6 require 'unicorn/const'
7 require 'unicorn/http_request'
8 require 'unicorn/configurator'
10 require 'unicorn/tee_input'
12 # autoload this so the app can prefer a different version, we
13 # don't rely on Rack itself for much and should be compatible for
15 autoload :Rack, 'rack'
17 # Unicorn module containing all of the classes (include C extensions) for running
18 # a Unicorn web server. It contains a minimalist HTTP server with just enough
19 # functionality to service web application requests fast as possible.
22 # raised inside TeeInput when a client closes the socket inside the
23 # application dispatch. This is always raised with an empty backtrace
24 # since there is nothing in the application stack that is responsible
25 # for client shutdowns/disconnects.
26 class ClientShutdown < EOFError
29 # we load HttpResponse last since it depends on Rack, and we
30 # want the application to be able to specify Rack (if they're
31 # *not* using config.ru)
32 autoload :HttpResponse, 'unicorn/http_response'
35 def run(app, options = {})
36 HttpServer.new(app, options).start.join
39 # This returns a lambda to pass in as the app, this does not "build" the
40 # app (which we defer based on the outcome of "preload_app" in the
41 # Unicorn config). The returned lambda will be called when it is
42 # time to build the app.
45 # parse embedded command-line options in config.ru comments
46 /^#\\(.*)/ =~ File.read(ru) and opts.parse!($1.split(/\s+/))
53 raw.sub!(/^__END__\n.*/, '')
54 eval("Rack::Builder.new {(#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru)
57 Object.const_get(File.basename(ru, '.rb').capitalize)
60 pp({ :inner_app => inner_app }) if $DEBUG
62 # return value, matches rackup defaults based on env
66 use Rack::CommonLogger, $stderr
67 use Rack::ShowExceptions
73 use Rack::CommonLogger, $stderr
82 # returns an array of strings representing TCP listen socket addresses
83 # and Unix domain socket paths. This is useful for use with
84 # Raindrops::Middleware under Linux: http://raindrops.bogomips.org/
86 HttpServer::LISTENERS.map { |io| SocketHelper.sock_name(io) }
90 # This is the process manager of Unicorn. This manages worker
91 # processes which in turn handle the I/O and application process.
92 # Listener sockets are started in the master process and shared with
93 # forked worker children.
95 class HttpServer < Struct.new(:app, :timeout, :worker_processes,
96 :before_fork, :after_fork, :before_exec,
97 :logger, :pid, :listener_opts, :preload_app,
98 :reexec_pid, :orig_app, :init_listeners,
99 :master_pid, :config, :ready_pipe, :user)
100 include ::Unicorn::SocketHelper
102 # prevents IO objects in here from being GC-ed
105 # all bound listener sockets
108 # This hash maps PIDs to Workers
111 # We use SELF_PIPE differently in the master and worker processes:
113 # * The master process never closes or reinitializes this once
114 # initialized. Signal handlers in the master process will write to
115 # it to wake up the master from IO.select in exactly the same manner
116 # djb describes in http://cr.yp.to/docs/selfpipe.html
118 # * The workers immediately close the pipe they inherit from the
119 # master and replace it with a new pipe after forking. This new
120 # pipe is also used to wakeup from IO.select from inside (worker)
121 # signal handlers. However, workers *close* the pipe descriptors in
122 # the signal handlers to raise EBADF in IO.select instead of writing
123 # like we do in the master. We cannot easily use the reader set for
124 # IO.select because LISTENERS is already that set, and it's extra
125 # work (and cycles) to distinguish the pipe FD from the reader set
126 # once IO.select returns. So we're lazy and just close the pipe when
127 # a (rare) signal arrives in the worker and reinitialize the pipe later.
130 # signal queue used for self-piping
133 # constant lookups are faster and we're single-threaded/non-reentrant
134 REQUEST = HttpRequest.new
136 # We populate this at startup so we can figure out how to reexecute
137 # and upgrade the currently running instance of Unicorn
138 # This Hash is considered a stable interface and changing its contents
139 # will allow you to switch between different installations of Unicorn
140 # or even different installations of the same applications without
141 # downtime. Keys of this constant Hash are described as follows:
143 # * 0 - the path to the unicorn/unicorn_rails executable
144 # * :argv - a deep copy of the ARGV array the executable originally saw
145 # * :cwd - the working directory of the application, this is where
146 # you originally started Unicorn.
148 # The following example may be used in your Unicorn config file to
149 # change your working directory during a config reload (HUP) without
150 # upgrading or restarting:
152 # Dir.chdir(Unicorn::HttpServer::START_CTX[:cwd] = path)
154 # To change your unicorn executable to a different path without downtime,
155 # you can set the following in your Unicorn config file, HUP and then
156 # continue with the traditional USR2 + QUIT upgrade steps:
158 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
160 :argv => ARGV.map { |arg| arg.dup },
162 # favor ENV['PWD'] since it is (usually) symlink aware for
163 # Capistrano and like systems
165 a = File.stat(pwd = ENV['PWD'])
166 b = File.stat(Dir.pwd)
167 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
175 # This class and its members can be considered a stable interface
176 # and will not change in a backwards-incompatible fashion between
177 # releases of Unicorn. You may need to access it in the
178 # before_fork/after_fork hooks. See the Unicorn::Configurator RDoc
180 class Worker < Struct.new(:nr, :tmp, :switched)
182 # worker objects may be compared to just plain numbers
187 # Changes the worker process to the specified +user+ and +group+
188 # This is only intended to be called from within the worker
189 # process from the +after_fork+ hook. This should be called in
190 # the +after_fork+ hook after any priviledged functions need to be
191 # run (e.g. to set per-worker CPU affinity, niceness, etc)
193 # Any and all errors raised within this method will be propagated
194 # directly back to the caller (usually the +after_fork+ hook.
195 # These errors commonly include ArgumentError for specifying an
196 # invalid user/group and Errno::EPERM for insufficient priviledges
197 def user(user, group = nil)
198 # we do not protect the caller, checking Process.euid == 0 is
199 # insufficient because modern systems have fine-grained
200 # capabilities. Let the caller handle any and all errors.
201 uid = Etc.getpwnam(user).uid
202 gid = Etc.getgrnam(group).gid if group
203 Unicorn::Util.chown_logs(uid, gid)
205 if gid && Process.egid != gid
206 Process.initgroups(user, gid)
207 Process::GID.change_privilege(gid)
209 Process.euid != uid and Process::UID.change_privilege(uid)
215 # Creates a working server on host:port (strange things happen if
216 # port isn't a Number). Use HttpServer::run to start the server and
217 # HttpServer.run.join to join the thread that's processing
218 # incoming requests on the socket.
219 def initialize(app, options = {})
222 self.ready_pipe = options.delete(:ready_pipe)
223 self.init_listeners = options[:listeners] ? options[:listeners].dup : []
224 self.config = Configurator.new(options.merge(:use_defaults => true))
225 self.listener_opts = {}
227 # we try inheriting listeners first, so we bind them later.
228 # we don't write the pid file until we've bound listeners in case
229 # unicorn was started twice by mistake. Even though our #pid= method
230 # checks for stale/existing pid files, race conditions are still
231 # possible (and difficult/non-portable to avoid) and can be likely
232 # to clobber the pid if the second start was in quick succession
233 # after the first, so we rely on the listener binding to fail in
234 # that case. Some tests (in and outside of this source tree) and
235 # monitoring tools may also rely on pid files existing before we
236 # attempt to connect to the listener(s)
237 config.commit!(self, :skip => [:listeners, :pid])
241 # Runs the thing. Returns self so you can run join on it
243 BasicSocket.do_not_reverse_lookup = true
245 # inherit sockets from parents, they need to be plain Socket objects
246 # before they become UNIXServer or TCPServer
247 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
248 io = Socket.for_fd(fd.to_i)
249 set_server_sockopt(io, listener_opts[sock_name(io)])
251 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
255 config_listeners = config[:listeners].dup
256 LISTENERS.replace(inherited)
258 # we start out with generic Socket objects that get cast to either
259 # TCPServer or UNIXServer objects; but since the Socket objects
260 # share the same OS-level file descriptor as the higher-level *Server
261 # objects; we need to prevent Socket objects from being garbage-collected
262 config_listeners -= listener_names
263 if config_listeners.empty? && LISTENERS.empty?
264 config_listeners << Unicorn::Const::DEFAULT_LISTEN
265 init_listeners << Unicorn::Const::DEFAULT_LISTEN
266 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
268 config_listeners.each { |addr| listen(addr) }
269 raise ArgumentError, "no listeners" if LISTENERS.empty?
271 # this pipe is used to wake us up from select(2) in #join when signals
272 # are trapped. See trap_deferred.
275 # setup signal handlers before writing pid file in case people get
276 # trigger happy and send signals as soon as the pid file exists.
277 # Note that signals don't actually get handled until the #join method
278 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
279 trap(:CHLD) { |_| awaken_master }
280 self.pid = config[:pid]
283 build_app! if preload_app
284 maintain_worker_count
288 # replaces current listener set with +listeners+. This will
289 # close the socket if it will not exist in the new listener set
290 def listeners=(listeners)
291 cur_names, dead_names = [], []
292 listener_names.each do |name|
294 # mark unlinked sockets as dead so we can rebind them
295 (File.socket?(name) ? cur_names : dead_names) << name
300 set_names = listener_names(listeners)
301 dead_names.concat(cur_names - set_names).uniq!
303 LISTENERS.delete_if do |io|
304 if dead_names.include?(sock_name(io))
305 IO_PURGATORY.delete_if do |pio|
306 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
308 (io.close rescue nil).nil? # true
310 set_server_sockopt(io, listener_opts[sock_name(io)])
315 (set_names - cur_names).each { |addr| listen(addr) }
318 def stdout_path=(path); redirect_io($stdout, path); end
319 def stderr_path=(path); redirect_io($stderr, path); end
322 HttpRequest::DEFAULTS["rack.logger"] = super
325 # sets the path for the PID file of the master process
328 if x = valid_pid?(path)
329 return path if pid && path == pid && x == $$
330 raise ArgumentError, "Already running on PID:#{x} " \
331 "(or pid=#{path} is stale)"
334 unlink_pid_safe(pid) if pid
338 tmp = "#{File.dirname(path)}/#{rand}.#$$"
339 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
344 File.rename(fp.path, path)
350 # add a given address to the +listeners+ set, idempotently
351 # Allows workers to add a private, per-process listener via the
352 # after_fork hook. Very useful for debugging and testing.
353 # +:tries+ may be specified as an option for the number of times
354 # to retry, and +:delay+ may be specified as the time in seconds
355 # to delay between retries.
356 # A negative value for +:tries+ indicates the listen will be
357 # retried indefinitely, this is useful when workers belonging to
358 # different masters are spawned during a transparent upgrade.
359 def listen(address, opt = {}.merge(listener_opts[address] || {}))
360 address = config.expand_addr(address)
361 return if String === address && listener_names.include?(address)
363 delay = opt[:delay] || 0.5
364 tries = opt[:tries] || 5
366 io = bind_listen(address, opt)
367 unless TCPServer === io || UNIXServer === io
371 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
374 rescue Errno::EADDRINUSE => err
375 logger.error "adding listener failed addr=#{address} (in use)"
376 raise err if tries == 0
378 logger.error "retrying in #{delay} seconds " \
379 "(#{tries < 0 ? 'infinite' : tries} tries left)"
383 logger.fatal "error adding listener addr=#{address}"
388 # monitors children and receives signals forever
389 # (or until a termination signal is sent). This handles signals
390 # one-at-a-time time and we'll happily drop signals in case somebody
391 # is signalling us too often.
394 last_check = Time.now
397 logger.info "master process ready" # test_exec.rb relies on this message
399 ready_pipe.syswrite($$.to_s)
400 ready_pipe.close rescue nil
401 self.ready_pipe = nil
408 # avoid murdering workers after our master process (or the
409 # machine) comes out of suspend/hibernation
410 if (last_check + timeout) >= (last_check = Time.now)
413 # wait for workers to wakeup on suspend
414 master_sleep(timeout/2.0 + 1)
416 maintain_worker_count if respawn
418 when :QUIT # graceful shutdown
420 when :TERM, :INT # immediate shutdown
423 when :USR1 # rotate logs
424 logger.info "master reopening logs..."
425 Unicorn::Util.reopen_logs
426 logger.info "master done reopening logs"
427 kill_each_worker(:USR1)
428 when :USR2 # exec binary, stay alive in case something went wrong
431 if Process.ppid == 1 || Process.getpgrp != $$
433 logger.info "gracefully stopping all workers"
434 kill_each_worker(:QUIT)
436 logger.info "SIGWINCH ignored because we're not daemonized"
439 self.worker_processes += 1
441 self.worker_processes -= 1 if self.worker_processes > 0
444 if config.config_file
446 redo # immediate reaping since we may have QUIT workers
447 else # exec binary and exit if there's no config file
448 logger.info "config_file not present, reexecuting binary"
457 logger.error "Unhandled master loop exception #{e.inspect}."
458 logger.error e.backtrace.join("\n")
461 stop # gracefully shutdown all workers on our way out
462 logger.info "master complete"
463 unlink_pid_safe(pid) if pid
466 # Terminates all workers, but does not exit master process
467 def stop(graceful = true)
469 limit = Time.now + timeout
470 until WORKERS.empty? || Time.now > limit
471 kill_each_worker(graceful ? :QUIT : :TERM)
475 kill_each_worker(:KILL)
480 # list of signals we care about and trap in master.
481 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
484 # defer a signal for later processing in #join (master process)
485 def trap_deferred(signal)
486 trap(signal) do |sig_nr|
487 if SIG_QUEUE.size < 5
491 logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
496 # wait for a signal hander to wake us up and then consume the pipe
497 # Wake up every second anyways to run murder_lazy_workers
498 def master_sleep(sec)
500 ready = IO.select([SELF_PIPE.first], nil, nil, sec) or return
501 ready.first && ready.first.first or return
502 loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
503 rescue Errno::EAGAIN, Errno::EINTR
509 SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
510 rescue Errno::EAGAIN, Errno::EINTR
511 # pipe is full, master should wake up anyways
516 # reaps all unreaped workers
520 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
522 if reexec_pid == wpid
523 logger.error "reaped #{status.inspect} exec()-ed"
525 self.pid = pid.chomp('.oldbin') if pid
528 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
529 logger.info "reaped #{status.inspect} " \
530 "worker=#{worker.nr rescue 'unknown'}"
537 # reexecutes the START_CTX with a new binary
541 Process.kill(0, reexec_pid)
542 logger.error "reexec-ed child already running PID:#{reexec_pid}"
550 old_pid = "#{pid}.oldbin"
553 self.pid = old_pid # clear the path for a new pid file
555 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
556 "existing pid=#{old_pid}, refusing rexec"
559 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
564 self.reexec_pid = fork do
565 listener_fds = LISTENERS.map { |sock| sock.fileno }
566 ENV['UNICORN_FD'] = listener_fds.join(',')
567 Dir.chdir(START_CTX[:cwd])
568 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
570 # avoid leaking FDs we don't know about, but let before_exec
571 # unset FD_CLOEXEC, if anything else in the app eventually
572 # relies on FD inheritence.
573 (3..1024).each do |io|
574 next if listener_fds.include?(io)
575 io = IO.for_fd(io) rescue nil
578 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
580 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
581 before_exec.call(self)
584 proc_name 'master (old)'
587 # forcibly terminate all workers that haven't checked in in timeout
588 # seconds. The timeout is implemented using an unlinked File
589 # shared between the parent process and each worker. The worker
590 # runs File#chmod to modify the ctime of the File. If the ctime
591 # is stale for >timeout seconds, then we'll kill the corresponding
593 def murder_lazy_workers
594 WORKERS.dup.each_pair do |wpid, worker|
595 stat = worker.tmp.stat
596 # skip workers that disable fchmod or have never fchmod-ed
597 stat.mode == 0100600 and next
598 (diff = (Time.now - stat.ctime)) <= timeout and next
599 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
600 "(#{diff}s > #{timeout}s), killing"
601 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
605 def spawn_missing_workers
606 (0...worker_processes).each do |worker_nr|
607 WORKERS.values.include?(worker_nr) and next
608 worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
609 before_fork.call(self, worker)
611 ready_pipe.close if ready_pipe
612 self.ready_pipe = nil
618 def maintain_worker_count
619 (off = WORKERS.size - worker_processes) == 0 and return
620 off < 0 and return spawn_missing_workers
621 WORKERS.dup.each_pair { |wpid,w|
622 w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
626 # if we get any error, try to write something back to the client
627 # assuming we haven't closed the socket, but don't get hung up
628 # if the socket is already closed or broken. We'll always ensure
629 # the socket is closed at the end of this function
630 def handle_error(client, e)
632 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
633 Const::ERROR_500_RESPONSE
634 when HttpParserError # try to tell the client they're bad
635 Const::ERROR_400_RESPONSE
637 logger.error "Read error: #{e.inspect}"
638 logger.error e.backtrace.join("\n")
639 Const::ERROR_500_RESPONSE
641 client.write_nonblock(msg)
647 # once a client is accepted, it is processed in its entirety here
648 # in 3 easy steps: read request, call app, write app response
649 def process_client(client)
650 client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
651 response = app.call(env = REQUEST.read(client))
653 if 100 == response.first.to_i
654 client.write(Const::EXPECT_100_RESPONSE)
655 env.delete(Const::HTTP_EXPECT)
656 response = app.call(env)
658 HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
660 handle_error(client, e)
663 # gets rid of stuff the worker has no business keeping track of
664 # to free some resources and drops all sig handlers.
665 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
667 def init_worker_process(worker)
668 QUEUE_SIGS.each { |sig| trap(sig, nil) }
669 trap(:CHLD, 'DEFAULT')
671 proc_name "worker[#{worker.nr}]"
674 WORKERS.values.each { |other| other.tmp.close rescue nil }
676 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
677 worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
678 after_fork.call(self, worker) # can drop perms
679 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
680 self.timeout /= 2.0 # halve it for select()
681 build_app! unless preload_app
684 def reopen_worker_logs(worker_nr)
685 logger.info "worker=#{worker_nr} reopening logs..."
686 Unicorn::Util.reopen_logs
687 logger.info "worker=#{worker_nr} done reopening logs"
691 # runs inside each forked worker, this sits around and waits
692 # for connections and doesn't die until the parent dies (or is
693 # given a INT, QUIT, or TERM signal)
694 def worker_loop(worker)
696 init_worker_process(worker)
697 nr = 0 # this becomes negative if we need to reopen logs
698 alive = worker.tmp # tmp is our lifeline to the master process
701 # closing anything we IO.select on will raise EBADF
702 trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
703 trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
704 [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
705 logger.info "worker=#{worker.nr} ready"
709 nr < 0 and reopen_worker_logs(worker.nr)
712 # we're a goner in timeout seconds anyways if alive.chmod
713 # breaks, so don't trap the exception. Using fchmod() since
714 # futimes() is not available in base Ruby and I very strongly
715 # prefer temporary files to be unlinked for security,
716 # performance and reliability reasons, so utime is out. No-op
717 # changes with chmod doesn't update ctime on all filesystems; so
718 # we change our counter each and every time (after process_client
719 # and before IO.select).
720 alive.chmod(m = 0 == m ? 1 : 0)
724 process_client(sock.accept_nonblock)
726 alive.chmod(m = 0 == m ? 1 : 0)
727 rescue Errno::EAGAIN, Errno::ECONNABORTED
732 # make the following bet: if we accepted clients this round,
733 # we're probably reasonably busy, so avoid calling select()
734 # and do a speculative accept_nonblock on ready listeners
735 # before we sleep again in select().
736 redo unless nr == 0 # (nr < 0) => reopen logs
738 ppid == Process.ppid or return
739 alive.chmod(m = 0 == m ? 1 : 0)
741 # timeout used so we can detect parent death:
742 ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
751 logger.error "Unhandled listen loop exception #{e.inspect}."
752 logger.error e.backtrace.join("\n")
757 # delivers a signal to a worker and fails gracefully if the worker
758 # is no longer running.
759 def kill_worker(signal, wpid)
761 Process.kill(signal, wpid)
763 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
767 # delivers a signal to each worker
768 def kill_each_worker(signal)
769 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
772 # unlinks a PID file at given +path+ if it contains the current PID
773 # still potentially racy without locking the directory (which is
774 # non-portable and may interact badly with other programs), but the
775 # window for hitting the race condition is small
776 def unlink_pid_safe(path)
777 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
780 # returns a PID if a given path contains a non-stale PID file,
783 wpid = File.read(path).to_i
784 wpid <= 0 and return nil
786 Process.kill(0, wpid)
789 # don't unlink stale pid files, racy without non-portable locking...
797 logger.info "reloading config_file=#{config.config_file}"
798 config[:listeners].replace(init_listeners)
801 kill_each_worker(:QUIT)
802 Unicorn::Util.reopen_logs
804 build_app! if preload_app
805 logger.info "done reloading config_file=#{config.config_file}"
806 rescue StandardError, LoadError, SyntaxError => e
807 logger.error "error reloading config_file=#{config.config_file}: " \
808 "#{e.class} #{e.message}"
809 self.app = loaded_app
813 # returns an array of string names for the given listener array
814 def listener_names(listeners = LISTENERS)
815 listeners.map { |io| sock_name(io) }
819 if app.respond_to?(:arity) && app.arity == 0
820 if defined?(Gem) && Gem.respond_to?(:refresh)
821 logger.info "Refreshing Gem list"
826 # exploit COW in case of preload_app. Also avoids race
827 # conditions in Rainbows! since load/require are not thread-safe
828 Unicorn.const_get :HttpResponse
833 $0 = ([ File.basename(START_CTX[0]), tag
834 ]).concat(START_CTX[:argv]).join(' ')
837 def redirect_io(io, path)
838 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
843 SELF_PIPE.each { |io| io.close rescue nil }
844 SELF_PIPE.replace(IO.pipe)
845 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }