简体   繁体   中英

Why can't I close SSH connection when having forked a process with ruby?

Consider the following Ruby script:

fork do
  loop do
    sleep 1
  end
end

As soon as I run this script on a Linux server I'm connected to via SSH, closing the SSH connection subsequently hangs (I have to exit it by typing ~ + RETURN , otherwise the connection remains open / keeps hanging. I'm using ruby 3.0.1p64 and the server OS is Fedora.

The problem even occurs when detaching from the forked process:

pid = fork do
  loop do
    sleep 1
  end
end

Process.detach(pid)

What solves this issue is redirecting stdout and stderr to /dev/null , but I need the output of the parent process to be visible so that's not a feasible solution:

ruby script.rb < /dev/null >& /dev/null

Why is that and is there a way around it?

Found the solution:

pid = fork do
  STDIN.reopen File.open("/dev/null", "r")
  null_out = File.open "/dev/null", "w"
  STDOUT.reopen null_out
  STDERR.reopen null_out

  loop do
    sleep 1
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM