XCode 优雅的程序关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21339289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:35:31  来源:igfitidea点击:

XCode graceful program shutdown

c++cxcode

提问by Gleno

I'm working on a server-like program in xcode, and I want it to shut down gracefully between debug runs. Basically the following line is not working

我正在 xcode 中开发一个类似服务器的程序,我希望它在调试运行之间正常关闭。基本上以下行不起作用

std::signal(SIGKILL, [](int){
    printf("got sigkill here!\n"); 
    //shut-down code here
});

I've tried trapping other signals, but so far SIGINT, SIGTERM and SIGABRT have not worked. How is xcode terminating the program, if it prints

我试过捕获其他信号,但到目前为止 SIGINT、SIGTERM 和 SIGABRT 还没有工作。xcode 如何终止程序,如果它打印

Program ended with exit code: 9

程序以退出代码结束:9

to the console?

到控制台?

EDITApparently SIGKILL can not be caught, see this wikipedia entry.

编辑显然无法捕获 SIGKILL,请参阅此维基百科条目。

In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal

与 SIGTERM 和 SIGINT 不同的是,这个信号不能被捕获或忽略,接收进程在收到这个信号后也不能进行任何清理

回答by Filipe Gon?alves

You can't catch SIGKILL. When a process receives SIGKILL, it immediately terminates. This is used to kill buggy processes that won't respond or ignore the regular SIGINT. If you could catch SIGKILL, and possibly ignore it, then there would be no way to kill a buggy process apart from rebooting the machine.

你抓不到SIGKILL。当一个进程收到 时SIGKILL,它立即终止。这用于杀死不会响应或忽略常规SIGINT. 如果您可以捕获SIGKILL并可能忽略它,那么除了重新启动机器之外,没有办法杀死有问题的进程。

Also, note that you're calling printf()in a signal handler, which is not allowed. You can't expect this to work.

另请注意,您正在调用printf()信号处理程序,这是不允许的。你不能指望这会奏效。

You can have a look at signal-safe functions in signalmanpage: http://man7.org/linux/man-pages/man7/signal.7.html- printfis not part of it, so all bets are off.

您可以在手册signal页中查看信号安全功能:http: //man7.org/linux/man-pages/man7/signal.7.html-printf不是它的一部分,所以所有的赌注都关闭了。

From the manpage:

从联机帮助页:

A signal handler function must be very careful, since processing elsewhere may be interrupted at some arbitrary point in the execution of the program. POSIX has the concept of "safe function". If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined.

信号处理函数必须非常小心,因为其他地方的处理可能会在程序执行的某个任意点被中断。POSIX 有“安全函数”的概念。如果一个信号中断了一个不安全函数的执行,并且处理程序调用了一个不安全函数,那么程序的行为是未定义的。

See this question for safe alternatives: Print int from signal handler using write or async-safe functions

请参阅此问题以获取安全替代方案:使用写入或异步安全函数从信号处理程序打印整数