Is there an example of a working timer that executes some function every x amount seconds using C.
I’d appreciate an example working code.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could spawn a new thread:
Or, you could set an alarm with
alarm(2)orsetitimer(2):Of course, both of these methods have the problem that the function you’re calling periodically needs to be thread-safe.
The signal method is particularly dangerous because it must also be async-safe, which is very hard to do — even something as simple as
printfis unsafe becauseprintfmight allocate memory, and if theSIGALRMinterrupted a call tomalloc, you’re in trouble becausemallocis not reentrant. So I wouldn’t recommend the signal method, unless all you do is set a flag in the signal handler which later gets checked by some other function, which puts you back in the same place as the threaded version.