gpt4 book ai didi

c++ - 为什么使用 memset() 初始化 sigint 变量有助于防止 Seg Faults?

转载 作者:行者123 更新时间:2023-12-01 14:41:15 26 4
gpt4 key购买 nike

背景:

struct sigaction 用于为处理中断的小型 C 程序设置处理程序。当我在完成第二个处理程序的实现后收到“段错误(核心转储)”错误消息时出现问题。我以完全相同的方式设置了两个处理程序。第一个中断处理程序在没有初始化 sigaction 结构的情况下工作正常,但是,当我完成第二个处理程序的实现时,我收到了 seg 错误错误。

问题:

为什么使用 memset() 初始化 sigaction 结构有助于修复错误?

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <string.h>

#define ALARMSECONDS 3
int numSigints = 5;

/* Handler function that prints out the current time on a SIGALRM interrupt. */
static void hdl(int signum)
{
time_t currTime;
time(&currTime);
printf("\ncurrent time is %s", ctime(&currTime));
alarm(ALARMSECONDS);//re-arm the alarm

}

/* Handler function that captures SIGINT interrupts 5 times before
actually exiting. Makes use of global variable to keep track of
number of times the interrupt was sent.
*/
static void sigint_hdl(int signum)
{

numSigints -= 1;

if(numSigints == 0)
{
printf("\nFinal Control-c caught. Exiting.\n");
exit(1);
}
else
{
printf("\nControl-c caught. %d more before program is ended.\n",
numSigints);
}
}

/* Periodically prints out the current time in Unix date format using
sigaction interrupt handling.
*/
int main(int argc, char *argv[])
{

//
// vars
//
struct sigaction act;
struct sigaction sigint_act;

memset(&act, '\0', sizeof(act));//TODO Why does this fix SEGFAULT???

//
// intro
//
printf("Date will be printed every 3 seconds.\n");
printf("Enter ^C 5 times to end the program.\n");

//
// set alarm to go off in 3 seconds
//
alarm(ALARMSECONDS);

//
// set handler of the sigaction to 'hdl' function defined above
//
act.sa_handler = hdl;
sigint_act.sa_handler = sigint_hdl;

//
// activate sigaction
//
if(sigaction(SIGALRM, &act, NULL) < 0)
{
perror("sigaction -- SIGALRM");
return 1;
}

if(sigaction(SIGINT, &sigint_act, NULL) < 0)
{
perror("sigaction -- SIGINT");
return 1;
}

//
// infinite loop
//
while(1) {
}

return 0;
}

最佳答案

sigaction 中有许多字段结构体。将它们全部设为零会将它们设置为默认值。

如果它们不是零,它们将按照系统调用文档中描述的任何方式进行解释。一个示例是两个字段 sa_masksa_sigaction .并取决于 sa_mask 的值, sa_sigaction handler 将被调用,而不是您的代码安装的预期信号处理程序。而且由于您没有初始化指针,因此它将具有一些垃圾值,并且将尝试不仅取消引用,而且通过垃圾指针调用函数。

因此,如果您未能初始化结构,您将获得未定义的行为。有时它会起作用,有时它不会以神秘的方式起作用,例如崩溃。

通过将整个结构清零,您可以确保默认行为将发生,正如您对结构所做的任何非默认设置所修改的那样。

经验教训:始终清除并初始化传递给库函数的所有结构。

关于c++ - 为什么使用 memset() 初始化 sigint 变量有助于防止 Seg Faults?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com