How should I close a socket in a signal handler?

醉酒当歌 提交于 2019-12-01 16:13:05

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

  • 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

  • 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.
MarkR

Normally, it's advisable not to do anything much in a signal handler; other than set a flag.

Then when control returns to your main loop you can examine this flag, exit the loop, close sockets, run destructors on your objects etc, and exit cleanly.

Signal handlers can get called at almost any time, including in the middle of C or C++ library calls, which could be a problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!