从终端正确关闭服务器的方法是什么?

huangapple go评论82阅读模式
英文:

What is the correct way to shut down a server from the terminal?

问题

我正在尝试使用Go语言进行一些基本的聊天(服务器+客户端)编程,所以我有一个监听特定端口的服务器和一个向该端口写入数据的客户端。

然而,由于我对此还不熟悉,我经常进行更改并且不得不重新启动服务器等等。每次我想停止服务器时,我都会使用"Ctrl + C",但这显然很愚蠢,因为我必须在每次编译时更改端口号...正确的做法是什么?目前我只是在服务器的主函数中建立连接后使用以下代码:

defer ln.Close()

但我猜Ctrl + C只是终止进程而不关闭连接?

编辑:更多信息。
我在Windows上运行cygwin。ps命令没有显示旧的进程,但我在任务管理器中找到了很多"server.exe"(我的服务器文件名为server.go)。

英文:

I am trying my hands on some basic chat (server + client) stuff in Go so I have a server which listens on a specific port and I have a client which writes to this port.

However, as I am new to this, I constantly make changes and have to restart the server etc. I've been doing 'Ctrl + C' everytime I want to stop server but this is obviously stupid as I have to change the port number on every compilation... What is the correct way of doing this? I'm currently just doing

defer ln.Close()

in the main function of the server after the connection has been established but I guess Ctrl + C just kills the process without closing the connection?

EDIT: More information.
I am running cygwin on Windows. ps shows no old processes but I found a looot of "server.exe" (my server file is named server.go) in the task manager.

答案1

得分: 1

除非你使用os/signal包来在按下Ctrl+C时通知你,否则你的延迟语句将不会被执行。

下面是一个处理SIGINT(Ctrl+C)以正常退出程序的示例。

func main() {
    done := make(chan os.Signal)
    go signal.Notify(done, syscall.SIGINT)

    go func() {
        // 在这里编写你的TCP服务器代码,并包含清理服务器的延迟语句
    }()

    <-done

    // 正常退出
}
英文:

Unless you are using os/signal package to Notify you when you hit Ctrl+C your defer statement will not get run.

Here is an example of a handled SIGINT (Ctrl+C) to exit a program cleanly.

func main() {
    done := make(chan os.Signal)
    go signal.Notify(done, syscall.SIGINT)

    go func() {
         // your tcp server goes here along with the defer to clean up your server
    }()

    &lt;-done

    // exit cleanly
}

huangapple
  • 本文由 发表于 2015年5月1日 00:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/29973382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定