开发者

Using long data inside signal handler.

开发者 https://www.devze.com 2023-03-24 04:00 出处:网络
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

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开发者_JAVA百科 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 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.

Sample 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;
}

If you want to use a shared variable other than sig_atomic_t use atomics (atomic_long_read, atomic_long_set).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号