我编写了这段代码来在守护进程中运行我的进程.目标是即使我关闭其父进程也要使此进程运行.现在,我希望能够在其标准输入中写一些东西.我该怎么办 ?这是代码.
def daemonize(cmd, options = {})
rd, wr = IO.pipe
p1 = Process.fork {
Process.setsid
p2 = Process.fork {
$0 = cmd #Name of the command
pidfile = File.new(options[:pid_file], 'w')
pidfile.chmod( 0644 )
pidfile.puts "#{Process.pid}"
pidfile.close
Dir.chdir(ENV["PWD"] = options[:working_dir].to_s) if options[:working_dir]
File.umask 0000
STDIN.reopen '/dev/null'
STDOUT.reopen '/dev/null', 'a'
STDERR.reopen STDOUT
Signal.trap("USR1") do
Console.show 'I just received a USR1', 'warning'
end
::Kernel.exec(*Shellwords.shellwords(cmd)) #Executing the command in the parent process
exit
}
raise 'Fork failed!' if p2 == -1
Process.detach(p2) # divorce p2 from parent process (p1)
rd.close
wr.write p2
wr.close
exit
}
raise 'Fork failed!' if p1 == -1
Process.detach(p1) # divorce p1 from parent process (shell)
wr.close
daemon_id = rd.read.to_i
rd.close
daemon_id
end
有没有办法在管道中重新打开stdin而不是/ dev / null,我可以在其中编写?
最佳答案 一个fifo怎么样?在linux中,您可以使用
mkfifo
命令:
$mkfifo /tmp/mypipe
然后你可以在那个管道上重新打开STDIN:
STDIN.reopen '/tmp/mypipe'
# Do read-y things
其他任何东西都可以写入该管道:
$echo "roflcopter" > /tmp/mypipe
允许ruby进程读取数据.
(更新)警告阻止
由于fifos阻塞直到读取和写入(例如读取被阻止,除非有写入,反之亦然),最好用多个线程处理.一个线程应该执行读取,将数据传递到队列,另一个线程应该处理该输入.以下是这种情况的一个例子:
require 'thread'
input = Queue.new
threads = []
# Read from the fifo and add to an input queue (glorified array)
threads << Thread.new(input) do |ip|
STDIN.reopen 'mypipe'
loop do
if line = STDIN.gets
puts "Read: #{line}"
ip.push line
end
end
end
# Handle the input passed by the reader thread
threads << Thread.new(input) do |ip|
loop do
puts "Ouput: #{ip.pop}"
end
end
threads.map(&:join)