C语言 在 C 中创建计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15348318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:39:55  来源:igfitidea点击:

Creating a Timer in C

ctimer

提问by Normal People Scare Me

How do I create a timer? A timer like the one in Visual Basic; you set an interval, if the timer is enabled it waits until the time is up.

如何创建计时器?类似于 Visual Basic 中的计时器;您设置了一个间隔,如果启用了计时器,它会一直等到时间到。

I don't want to use an existing library because I want to know how it works.

我不想使用现有的库,因为我想知道它是如何工作的。

So.. I just hope someone could explain me how timers work and maybe give me an example of code to create my own - if it's not too advanced.

所以..我只是希望有人能解释我定时器是如何工作的,也许给我一个代码示例来创建我自己的代码 - 如果它不是太先进的话。

Edit: I wanna create one for a linux system.

编辑:我想为 linux 系统创建一个。

回答by Bryan Olivier

The following is a very basic example which will run under Linux. If you look at the manual page of signalyou will see it is deprecated in favor of sigaction. Important is not to forget the volatile, otherwise the whileloop may not terminate depending on optimizations. Note also how SIGALRMis a highly shared resource which may be used by other timer facilities and there is only one.

下面是一个非常基本的例子,它将在 Linux 下运行。如果您查看手册页,signal您会发现它已被弃用,而支持sigaction. 重要的是不要忘记volatile,否则while循环可能不会根据优化而终止。还要注意SIGALRM一个高度共享的资源是如何被其他计时器设施使用的,而且只有一个。

The program will print Waitingfor three seconds and than quit after printing Finally ...once.

程序将打印Waiting三秒钟,然后在打印Finally ...一次后退出。

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

volatile int mark = 0;

void trigger(int sig)
{
        mark = 1;
}

int main(void)
{
        signal(SIGALRM, trigger);
        alarm(3);

        while (!mark)
        {
                printf("Waiting\n");
        }
        printf("Finally ...\n");

        return 0;
}

回答by LtWorf

You can do that

你可以这样做

#include <stdio.h>
#include <unistd.h>

int main() {
    printf("wait\n");
    sleep(3);
    printf("time elapsed\n");
    return 0;
}