Creating a Timer in C

2019-02-26 09:01发布

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.

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.

标签: c timer
2条回答
欢心
2楼-- · 2019-02-26 09:13

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

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

#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;
}
查看更多
Explosion°爆炸
3楼-- · 2019-02-26 09:20

You can do that

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

int main() {
    printf("wait\n");
    sleep(3);
    printf("time elapsed\n");
    return 0;
}
查看更多
登录 后发表回答