传递参数信号处理程序

传递参数信号处理程序

本文介绍了提供/传递参数信号处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以提供/传递任何参数到信号处理?

Can I provide/pass any arguments to signal handler?

/* Signal handling */
struct sigaction act;
act.sa_handler = signal_handler;
/* some more settings */

现在,处理程序是这样的:

Now, handler looks like this:

void signal_handler(int signo) {
    /* some code */
}

如果我想要做一些特别的东西,即删除临时文件,可以提供我这些文件作为参数传递给此处理?

If I want to do something special i.e. delete temp files, can I provide those files as an argument to this handler?

编辑0:谢谢你的答案。我们一般避免/鼓励使用全局变量。在这种情况下,如果你有一个庞大的计划,东西可以在不同的地方去错了,你可能需要做大量的清理。为什么这个API设计成这样?

Edit 0: Thanks for the answers. We generally avoid/discourage use of global variables. And in this case, If you have a huge program, things can go wrong at different places and you might need to do a lot of cleanup. Why was the API designed this way?

推荐答案

您不能传递到信号处理程序作为参数你自己的数据。相反,你必须保存在全局变量的参数。 (而且是真的,真的小心,如果您需要的变更的这些数据在安装信号处理程序后)。

You can't have data of your own passed to the signal handler as parameters. Instead you'll have to store your parameters in global variables. (And be really, really careful if you ever need to change those data after installing the the signal handler).

响应编辑0:的历史原因。信号是真的老了,真正的低层次的设计。基本上你刚才的内核的单一地址一些机器code和要求它去这个特定的地址,如果这样或那样的情况发生。我们回到这里的便携式汇编的心态,其中的内核提供了一个没有廉价的基准服务,无论用户进程可以合理地预期,为自己,它必须做自己。

Response to edit 0: Historical reasons. Signals are a really old and really low-level design. Basically you're just given the kernel a single address to some machine code and asking it to go to this specific address if such and such happens. We're back in the "portable assembler" mindset here, where the kernels provide a no-frills baseline service, and whatever the user process can reasonably be expected to to for itself, it must do itself.

此外,对全局变量通常的论点并不完全适合在这里。信号处理程序的本身的是一个全局设置,所以周围有它几个不同的套用户指定的参数没有相关的可能性。

Also, the usual arguments against global variables don't really apply here. The signal handler itself is a global setting, so there is no relevant possibility of having several different sets of user-specified parameters for it around.

这篇关于提供/传递参数信号处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:51