我应该如何关闭信号处理程序中的套接字? [英] How should I close a socket in a signal handler?

查看:105
本文介绍了我应该如何关闭信号处理程序中的套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常简单的服务器,该服务器将一直循环直到按下Ctrl-C为止.我想让ctrl-c的信号处理程序关闭打开的套接字并关闭服务器,但是我不知道信号处理程序的范围是什么,而且我不喜欢声明套接字的想法(s)我需要接近全球化.

I'm writing a very simple server that loops forever until Ctrl-C is pressed. I'd like to have the signal handler for ctrl-c close the open sockets and shut down the server, but I don't know what the scope is for a signal handler, and I don't like the idea of declaring the socket(s) I would need to close to be global.

有人可以提供建议吗?有一些标准的方法可以做到这一点吗?

Can someone offer suggestions? Is there some standard way to do this?

推荐答案

好吧,由于您具有信号处理程序,因此我假设您使用的是Unix变体.如果是这样:

Well, since you have signal handlers, I'm going to assume you're on a Unix variant. If so:

  • 套接字是通过文件号(它是int)标识到内核的.参见socket(2).
  • 该int对您的流程有效
  • 该int对创建它后的所有分支有效
  • 如果未关闭执行,则对您执行的任何进程均有效.
  • A socket is identified to the kernel by the file number, which is an int. See socket(2).
  • That int is valid for your process
  • That int is valid for any processes forked after creating it
  • If not close-on-exec, it is valid for any process you exec.

因此,它在信号处理程序中完全有效.如何使信号处理程序知道要使用哪个数字,取决于您所使用的语言(未指定语言).有两种方法几乎可以在任何语言中使用

So, it's perfectly valid in your signal handler. How you make your signal handler aware of which number to use depends on the language you're writing in, which you didn't specify. There are two approaches that will work in pretty much any language

  • 如果除了close以外没有任何其他清除操作,请退出,只需调用exit.或将信号动作设置为默认值,即退出.内核将关闭套接字.
  • 设置一个标志(通常是某种全局变量),以告诉您的select/poll循环清理并退出.优点在于您不必担心程序的各个部分是否可以安全地从信号处理程序中调用.
  • If you don't have any cleanup to do except close and exit, just call exit. Or set the signal action to default, which is exit. The kernel will close the sockets.
  • Set a flag (which will generally be a global of some sort) to tell your select/poll loop to clean up and exit. Advantageous in that you don't have to worry about if various parts of your program are safe to call from a signal handler.

这篇关于我应该如何关闭信号处理程序中的套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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