0

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?

1
  • 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
    – user78252
    CommentedMar 12, 2013 at 12:01

3 Answers 3

2

You don't need threads to solve this. Use select() instead. I googled this answer which uses that approach: https://stackoverflow.com/questions/7226603/timeout-function

1
  • Beware of select() on Windows as if I recall correctly, it can only be used with sockets, not other file handles.
    – user53141
    CommentedNov 4, 2014 at 19:39
0

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.

2
  • 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?CommentedMar 12, 2013 at 3:46
  • 1
    @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.CommentedMar 12, 2013 at 7:39
0

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.

1
  • 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?CommentedNov 4, 2014 at 19:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.