windows – How to interrupt reading by timer?


Program in C, OS – Windows XP, compiler – MinGW GCC 3.4.5. We need an analogue alarm()SIGALRM . This is not available in MinGW. Instead of alarm() I used timeSetEvent() from libwinmm.a . The callback works, but read() (actually gets() from the console) is not interrupted (by SIGINT ( ^C ) it is interrupted). Calling raise ( SIGILL ) from Callback doesn't help. It seems that Callback and the main program are different threads, and raise generates a signal in the current thread, that is, in the Callback thread.

How to send a signal (in MinGW implementation) to another thread? At the same time, how to determine the current thread (unfortunately, I'm not strong in Windows)? How else can you interrupt waiting for input? It is desirable to receive:

read() == -1; errno == EINTR.

Actually, the task is to emulate alarm() , that is, to call the subroutine after a given time. A very useful side effect is to interrupt a system call (especially a pending event) while the timer was running (the system call). The solution for the specific case using setjmp() is obvious, we would like to do without it (or hide it as much as possible at the level of the alarm() call).


@duff, @timur, thank you for your attention.

I want to make an alarm() for MinGW (Windows) with behavior similar to SYSV Unix (that is, a blocking system call (for example read() is interrupted when the timer fires).

Generally speaking, when alarm() is called, it is not known whether the blocking will be on the socket, on the console, or on sleep ( Sleep() ). It is advisable to interrupt ANY wait. Unfortunately, I practically don’t know WinAPI, so I don’t know how from the function called by the CallBack timer:

  1. determine if the thread with main() is waiting. (waiting for some semaphore in the kernel?) (assuming a single-threaded scheme from the point of view of the programmer calling alarm() ).
  2. interrupt the wait with a return from the system call (perhaps it is correct to speak of a WinAPI function?) with a meaningful result.

If possible, in more detail about where to read about kbhit , ReadFile , CancelIO .

I hope I understood correctly (especially the HashCode).

I thank everyone for the advice on WinAPI, I will study and try.

Sincerely yours, avp


In order not to block input, you can try:

  • for POSIX – kbhit + select ;
  • for WinAPI – ReadFile + CancelIO .

I reread the question again. If you just need to interrupt reading on a timer, then select is the best option.

To implement alarm() for MinGW, you have to work with the Windows API (I don't see any other way). You will need

  • CreateThread
  • WaitForSingleObject
  • SetWaitableTimer

These and other functions that you will need, as well as examples of their use, are best read directly on MSDN.

Scroll to Top