c - 使用 sigaction 将信号处理行为重置为默认值

标签 c

我有一段代码是这样的:

struct sigaction sigtstp_act;

sigtstp_act.sa_handler = sigtstp_handler;
sigemptyset(&sigtstp_act.sa_mask);
sigtstp_act.sa_flags = 0;

sigaction(SIGTSTP, &sigtstp_act, NULL);

这是处理程序的代码:

void sigtstp_handler(int signo) {
    printf("SIGTSTP received. Going to new file...\n");
    fclose(f);
    goto_next_file();
    return;
}

这是 go_to_next_file 函数:

void go_to_next_file() {
  //Increments file_number, opens a new file to write to.
  file_number  += 1;

  char filename[32];
  snprintf(filename, sizeof(char) * 32, "%i.txt", file_number);

  f = fopen(filename, "w");
  //Check if opening a new file was successful.
  if (f == NULL)
  {
    printf("Error opening file!\n");
    exit(1);
  }
}

但是在第一次 SIGTSTP 发生后,我的处理程序被删除并恢复默认行为。 如何通过 sigaction() 永久安装我的处理程序?

最佳答案

您应该避免在信号处理程序中调用不安全的函数。它会导致未定义的行为,如 manual 中所述:

If a signal interrupts the execution of an unsafe function, and handler either calls an unsafe function or handler terminates via a call to longjmp() or siglongjmp() and the program subsequently calls an unsafe function, then the behavior of the program is undefined.

您可以在手册中看到安全功能列表。您的大部分功能不在列表中。最好的方法是在信号处理程序中设置一个 volatile 标志,并在主程序执行中处理所有内容。

关于c - 使用 sigaction 将信号处理行为重置为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501942/

相关文章:

接收TCP数据流的C程序

c++ - 函数 `feof` 总是返回 1

c - fread 到达 eof 时的缓冲区条件

c - Jansson lib 解析器

c - 是否可以在字符串化宏之前处理数学计算?

c - 在链表中添加冗余节点

在 C 中创建和初始化用户定义类型的数组

c - 使用 CUDA 5 的 cudaMemcpyToSymbol 出错

c - glutPostRedisplay 在不同的线程中

转换函数指针