Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to put a time limit on the user input, so if they take longer than 2 seconds to put type in an input then the program will terminate. I was wondering if there is a simple way to do this in C language?

share|improve this question
Just a side thought, people with slower / older computers could easily take longer than 2 seconds to go from starting the timer to rendering it on screen and having the user notice and having time to respond and having time to submit and then get that to the place where you stop the timer – RhysW Mar 12 '13 at 12:01

You don't need threads to solve this. Use select() instead. I googled this answer which uses that approach:

share|improve this answer
Beware of select() on Windows as if I recall correctly, it can only be used with sockets, not other file handles. – Steven Burnap Nov 4 '14 at 19:39

One simple way to do this would be to spawn a thread that will create a timer for two seconds and end the program if it hasn't received input. Create the thread before your blocking read call, set some sort of flag on input and read the flag in your timeout handler. Note you will need to make this thread safe.

share|improve this answer
I have never done that before, so I don't know what a thread is... What about if I took the timestamps before and after and then checked it 2 seconds has elapsed? – user2159166 Mar 12 '13 at 3:46
@user2159166: That will detect if the input operation took longer than the time-limit, but it will not interrupt the input at the moment the time-limit expires. – Bart van Ingen Schenau Mar 12 '13 at 7:39

You can just use alarm() before calling the input functtion and write a signal handler for SIGALRM and terinate your program in the signal handler.

share|improve this answer
Generating a signal and handling it is a legitimate way to handle async events in C, but it's probably beyond the abilities of a novice user to do it right/well/reliably. Can you provide some example code showing how it's done? – Jonathan Eunice Nov 4 '14 at 19:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.