【问题标题】:How to mask a signal when I handle a variable in signal _handler and in main function当我在信号 _handler 和主函数中处理变量时如何屏蔽信号
【发布时间】:2020-05-25 13:44:34
【问题描述】:

我正在尝试将内容从一个文件复制到另一个文件,使用 SIGINT 程序会中断以打印复制的字节数。我尝试在标志初始化、标志检查和标志清除时使用 sigprocmask 以避免竞争条件。但我不知道如何检查这个 sigprocmask 是否有效。我一直在努力找出这个问题。


void signal_handler(int num)
{
    flag = 1;
}
int main()
{
    signal(SIGINT, signal_handler);
    ret = sigaddset(&set, SIGINT);  
     /* Code for 
      * copying the bytes from one file to another
      */
    sigprocmask(SIG_BLOCK, &set, NULL);         
    if (flag == 1)
        printf("The number of bytes copied are :%llu\n", bytes); 
    flag = 0;
    sigprocmask(SIG_UNBLOCK, &set, NULL);
    }
}

【问题讨论】:

    标签: c linux unix io sigint


    【解决方案1】:

    它应该可以按您的预期工作。您唯一需要确保的是flagvolatile sig_atomic_t 类型,以避免flag 上的数据竞争。

    这是一个例子。循环连续打印bytes 的值(当bytes 达到UINT64_MAX 时,它会在某个时刻回绕)。您可以反复发送SIGINT进行测试。

    #include <stdio.h>
    #include <signal.h>
    #include <inttypes.h>
    
    volatile sig_atomic_t flag = 0;
    
    void signal_handler(int num)
    {
        flag = 1;
    }
    
    int main(void)
    {
        uint64_t bytes = 0;
        sigset_t set;
    
        signal(SIGINT, signal_handler);
        int ret = sigaddset(&set, SIGINT);
    
        while(1) {
            bytes++;
            sigprocmask(SIG_BLOCK, &set, NULL);
            if (flag == 1)
                printf("The number of bytes copied are :%" PRIu64 "\n", bytes);
            flag = 0;
            sigprocmask(SIG_UNBLOCK, &set, NULL);
        }
    }
    

    【讨论】:

    • 非常感谢。我已经发布这个问题很长时间了,但我没有得到任何回应。我是初学者,理解 sigprocmask 并不难。这个问题只是在没有任何评论或建议的情况下被否决。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2023-03-13
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多