c - 对C的定时器有一些困惑

标签 c linux timer

我想制作一个计时器,它会在一定时间间隔后调用我的函数,然后继续。 每当我的特定过程完成时,我就想停止这个计时器。 这里我有一个函数,我想在一定时间后调用它,但我想在这个函数中传递参数。

我的问题如下。

  1. 如何将参数传递给此函数?
  2. 有什么方法可以实现这个目标。

目前我正在使用这段代码。请阅读我在代码之间写的代码注释,以便您了解我的目标。

代码:

#include <stdio.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <signal.h>

int main()
{
    int result = 10;
    int i =0;

    // here I make timer which calls getP() function and I want to pass some
    // parameter to my getP function from here.
    // I don't want to make these variables global.
    initSigaction();
    initTime();
    // other process thread. If this process will be completed then I have to stop timer.
    pauseTime();
}

void initSigaction(void)
{
    struct sigaction act;
    act.sa_handler = getP;//;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGPROF, &act, NULL);
}

void initTime(void)
{
    struct itimerval val;
    //printDebugLog(WIFI,"Timer value : %d",TIMER);
    val.it_value.tv_sec = 1;
    val.it_value.tv_usec = 0;
    val.it_interval = val.it_value;
    printf("\nProgress Timer started\n");
    setitimer(ITIMER_PROF, &val, NULL);
}


void getP()
{
    // I want to get some parameter from main function and want to do some
    // calculation on this.  How can I get that parameter?
    printf("HI Hello");
}

int pauseTime(void)
{
    struct itimerval val;
    val.it_value.tv_sec = 0;
    val.it_value.tv_usec = 0;
    val.it_interval = val.it_value;
    setitimer(ITIMER_PROF, &val, NULL);
    printf("\n Stop Progress Timer\n");
    return EXIT_SUCCESS;
}

最佳答案

您可能想退后一步;您可以在信号处理程序中安全调用的函数集非常有限 - 请参阅 signal(2) .

一种策略是在信号处理程序中简单地增加一个变量(类型为 sig_atomic_t),然后在别处检查此标志。

关于c - 对C的定时器有一些困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546183/

相关文章:

linux 在设置我的 latex PATH 时,如果我退出,PATH 只会在终端窗口的持续时间内保持其值,我每次都必须重置

linux - sudo 关闭后启动 Raspberry Pi?

c - 为什么 lseek(fd1,0,SEEK_END) 等于文件大小 + 1?

c - 读取指针数据

c - 如何在障碍处正确同步线程

c - Parasoft 跳过所有文件而不进行测试

javascript - 随着时间间隔改变背景颜色

c - 如何避免定时器堆栈

java - 单击按钮时清除 JLabel 中的文本

将数组转换为无符号整数