在信号处理程序内使用长数据。 [英] Using long data inside signal handler.
问题描述
如何在信号处理程序中设置 long
(64位机器= 8字节)类型的变量?我已经读过,你只能使用类型 sig_atomic_t
的变量,它实际上实现为 volatile int
处理程序,并且修改大于 int
的数据类型是不安全的。
How can I set a variable of type long
(on 64 bit machine = 8 bytes) inside a signal handler? I've read that you can only use variables of type sig_atomic_t
, which is actually implemented as volatile int
inside a signal handler and it is unsafe to modify data types bigger than an int
.
推荐答案
You 可以在信号处理程序中使用 long
,实际上可以使用任何东西。你应该注意的唯一的事情是正确的同步,以避免竞争条件。
You can use a long
inside a signal handler, you can use anything, in fact. The only thing you should take care of is proper synchronization in order to avoid race conditions.
sig_atomic_t
用于在信号处理程序和其余代码之间共享的变量。对信号处理程序的任何变量private可以是任何类型,任何大小。
sig_atomic_t
should be used for variables shared between the signal handler and the rest of the code. Any variable "private" to the signal handler can be of any type, any size.
示例代码:
#include <signal.h>
static volatile long badShared; // NOT OK: shared not sig_atomic_t
static volatile sig_atomic_t goodShared; // OK: shared sig_atomic_t
void handler(int signum)
{
int localInt = 17;
long localLong = 23; // OK: not shared
if (badShared == 0) // NOT OK: shared not sig_atomic_t
++badShared;
if (goodShared == 0) // OK: shared sig_atomic_t
++goodShared;
}
int main()
{
signal(SOMESIGNAL, handler);
badShared++; // NOT OK: shared not sig_atomic_t
goodShared++; // OK: shared sig_atomic_t
return 0;
}
如果要使用除 sig_atomic_t
使用原子( atomic_long_read
, atomic_long_set
)。
If you want to use a shared variable other than sig_atomic_t
use atomics (atomic_long_read
, atomic_long_set
).
这篇关于在信号处理程序内使用长数据。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!