开发者

alarm function on Linux and Windows -> can't find a equivalent for Windows -> C

I have worked for some time now on Linux and done some C programs, and now I need to build an app for windows but is not being easy to find a replacement for the alarm function (found on signal.h)...

The thing is, in Linux, when you set the alarm flag as SIGALRM (if not mistaken), what the OS is going to do is to execute some function when the alarm goes off. Example:

signal(SIGALRM, myfunc);
alarm (2);

What is going to happen on this example is the OS is going to call the function myfunc开发者_StackOverflow every 2 seconds (in windows is going to be miliseconds probably, but don't mind that detail right now).

I've searched for some time how to do the same on windows (only using windows.h atm) but I can't find a replacement for that (searched thousands of times on msdn), and, on windows there is no SIGALRM flag on the signal.h.....

What can I use in C to do the same behaviour as the alarm with the SIGALRM flag?(In other words, a function that allows to execute another function using an alarm or similar).


Check the MSDN for timeSetEvent. It's not exactly the same as alarm, but may be close enough.


Using alarm/SIGALRM is not a safe way to "run a function at a given time" because the function gets invoked in a signal handling context where use of nearly any library functions is unsafe. Really the only good use I know of for SIGALRM is setting up a do-nothing signal handler with sigaction to interrupt system calls so that a system call you expect might hang gets interrupted with EINTR.

If you want to perform a given task N seconds from now, the safest way to do it is start a new thread that sleeps N seconds then performs the task. This should work on any operating system with threads.

Windows also has its own sort of timer events that can be delivered via the windows message system, but using them will make your code much more Windows-centric.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜