进程和 TCPSocket 在水晶中没有正确关闭 [英] Process and TCPSocket not close properly in crystal

查看:42
本文介绍了进程和 TCPSocket 在水晶中没有正确关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a tcp server who accept all the connection and execute incomming data has command line, but when i send "exit" to the tcpsocket, the process and the socket dont close properly

# 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退出,打印进程结束",程序关闭

for example, the following code work fine, after sending "exit" to STDIN, the shell is exiting, "process ending" is printedand the program close

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 套接字之前从未打印进程结束"

for debuggin purpose i have tested this code too but "process ending" was never print until i manually close the tcp socket

# 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 并发送exit"时,我希望套接字正确关闭,但他没有,当我发送更多命令时,程序会引发错误

when i run main.cr, nc localhost 2022 and send "exit" i expect the socket close properly but he dont, and when i send more command the program raise an error

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 ???

推荐答案

这是 Crystal 的一个已知问题.这里有一个问题:

This is a known issue with Crystal. There is an issue open here:

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

这篇关于进程和 TCPSocket 在水晶中没有正确关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆