水晶中的进程和TCPSocket无法正确关闭

时间:2019-06-18 09:31:32

标签: tcp process crystal-lang

我正在创建一个接受所有连接并执行传入数据的tcp服务器,该命令具有命令行,但是当我向tcpsocket发送“退出”消息时,进程和套接字无法正确关闭

# main.cr

require "socket"

PORT = 2022

def handle_connection(socket)
  Process.run("/bin/sh", input: socket, output: socket, error: socket)
end

server = TCPServer.new(PORT)

loop do
  if socket = server.accept?
    spawn handle_connection(socket)
  else
    break
  end
end

例如,以下代码可以正常工作,将“ exit”发送到STDIN之后,shell退出,打印“ process end”并关闭程序

channel = Channel(Nil).new

spawn do
  Process.run("/bin/sh", input: STDIN, output: STDOUT, error: STDERR)
  puts "process ending"
  channel.send(nil)
end

channel.receive

出于调试目的,我也测试了此代码,但是直到手动关闭tcp套接字,才打印“进程结束”

# main.cr

require "socket"

PORT = 2022

def handle_connection(socket)
  Process.run("/bin/sh", input: socket, output: socket, error: socket)
  puts "process ending"
end

server = TCPServer.new(PORT)

loop do
  if socket = server.accept?
    spawn handle_connection(socket)
  else
    break
  end
end

当我运行main.cr,nc localhost 2022并发送“退出”消息时,我期望套接字可以正确关闭,但是他没有,当我发送更多命令时,程序会引发错误

Unhandled exception in spawn: Error writing file: Broken pipe (Errno)
  from /usr/lib/crystal/crystal/system/unix/file_descriptor.cr:79:13 in 'unbuffered_write'
  from /usr/lib/crystal/io/buffered.cr:122:14 in 'write'
  from /usr/lib/crystal/io.cr:1130:7 in 'copy'
  from /usr/lib/crystal/process.cr:413:7 in 'copy_io'
  from /usr/lib/crystal/process.cr:409:11 in 'copy_io:close_dst'
  from /usr/lib/crystal/process.cr:298:17 in '->'
  from /usr/lib/crystal/fiber.cr:255:3 in 'run'
  from /usr/lib/crystal/fiber.cr:47:34 in '->'
  from ???

1 个答案:

答案 0 :(得分:0)

这是Crystal的已知问题。这里有一个未解决的问题:

https://github.com/crystal-lang/crystal/issues/7810