利用信号处理函数里面长数据。 [英] Using long data inside signal handler.

查看:104
本文介绍了利用信号处理函数里面长数据。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能设置类型的变量信号处理器中(64位机= 8个字节)?我读过,你只能使用一个信号内键入 sig_atomic_t ,这实际上是为挥发性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 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 应该用于信号处理程序和code其余部分之间的共享变量。任何变量私有的信号处理程序是的所有的类型的所有的大小。

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.

样code:

#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屋!

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