c - 使用 linux create_timer 和 sigaction API 时出现段错误

标签 c linux timer segmentation-fault sigaction

我正在尝试将以下代码集成到在 ARM<->DSP 系统上运行的更大的程序(不幸的是,我无法共享):

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

#define CLOCKID CLOCK_REALTIME
#define SIG SIGUSR1

timer_t timerid;

int i = 0;
int sec = 0;

volatile int keep_going = 1;

clock_t curr_time = 0, t_old = 0;

static void handler(int sig)
{
    curr_time = clock();
    if ((curr_time - t_old)/CLOCKS_PER_SEC >= 10.)
    keep_going = 0;
}

int main(int argc, char *argv[])
{
    struct sigevent sev;
    struct itimerspec its;
    long long freq_nanosecs;
    sigset_t mask;
    struct sigaction sa;
    memset(&sa, 0, sizeof sa);

    // Timer settings
    printf("Establishing handler for signal %d\n", SIG);
    sa.sa_flags = SA_SIGINFO;
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIG, &sa, NULL);

    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIG;
    sev.sigev_value.sival_ptr = &timerid;
    timer_create(CLOCKID, &sev, &timerid);

    /* Start the timer */
    its.it_value.tv_sec = 0;
    its.it_value.tv_nsec = 1000;
    its.it_interval.tv_sec = its.it_value.tv_sec;
    its.it_interval.tv_nsec = its.it_value.tv_nsec;

    timer_settime(timerid, 0, &its, NULL);
    t_old = clock();
    while(keep_going);
    printf("%f sec passed..\n", (double)(curr_time - t_old)/CLOCKS_PER_SEC);
    exit(EXIT_SUCCESS);
}

如您所见,这是一个非常简单的代码,在系统上单独运行时,它运行良好。这里的while循环只是为了演示,可以忽略。 处理程序和初始化步骤相同。

当我试图将它与更大的程序集成时,问题就开始了 - 突然,如果我设置的计时器间隔短于 10 毫秒,我会出现段错误。

我试图将处理程序中的操作减少到简单的一行,'curr_time = 0',认为它可能与处理程序中的浮点操作有关,但没有帮助。

应该注意的是,我为 ARM<->DSP 共享内存缓冲区使用了连续内存分配 API,尽管我怀疑这与它有任何关系,因为我没有在处理程序中分配任何新内存。

那么,有人知道段错误的可能原因吗?

最佳答案

核心转储总是对 SEGFAULT 有帮助:

$ ulimit -c unlimited

现在运行您的应用程序,在出现段错误后,您的当前目录中必须有一个“核心”文件。

现在使用GDB转储:

gdb <executable> -c <core-file>

您现在可以看到出现段错误的地方。 如果您有多线程应用程序,请在 gdb-console 中写入此行

$ gdb thread apply all bt

关于c - 使用 linux create_timer 和 sigaction API 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32169480/

相关文章:

c - GCC 编译错误 : format ‘%c’ expects argument of type ‘char *’ , 但参数 2 的类型为 ‘int’ [-Wformat]

java - 在java中通过套接字发送大数据

mysql - 通过 Linux 终端创建 MySQL 数据库并通过 phpMyAdmin 连接它

java - Wicket 应用程序、序列化和 Java 计时器

javascript - 如何在jQuery中传递和设置 slider 图像显示时间?

C指针问题

c - 在C中,函数是在第一次调用时加载到内存中还是在程序启动时加载到内存中?它可以从内存中卸载吗?

linux - bash 脚本 "top: -p requires argument"

linux - 如何在Kali Linux中的Wireshark中更改选项的颜色?

objective-c - 如何记录应用程序 session 持续时间?