[英]How to mask a signal when I handle a variable in signal _handler and in main function
我正在嘗試將內容從一個文件復制到另一個文件,使用 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);
}
}
它應該按您的預期工作。 您唯一需要確保的是flag
是volatile 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.