-3

How can you create C program that waits for user input for a specific number of seconds? After the time limit, the program closes, with or without input. Sample code please, using fork() and sleep(). Sorry I'm new at this.

Whoa. Sorry guys. This is not my post. Seems like someone used my account. And I can't delete it.

Sakamoto
  • 155
  • 2
  • 2
  • 14

3 Answers3

1

If you just want to sit the program down and wait... Make a loop checking for the input, use save the start time of the clock in a variable. Update the end time. Check in the loop if the time (here 5 seconds) has expired.

begin_t = clock();

// do-loop

   /* read user input*/
   end_t = clock();
// while( end_t - begin_t < 5 * CLOCKS_PER_SEC ) 
RisingSun
  • 2,407
  • 2
  • 16
  • 11
1

In my opinion usng fork() and sleep() is not the best way to achieve such a result. It's much better to use select() call which allows to wait for data with a timeout.

See the unix manual page on select() for some exemplary code.

Michał Wróbel
  • 684
  • 4
  • 10
1

The correct way to do this is to select STDIN for reading and set the timeout for however long you want. Select will either return STDIN as available for reading or return nothing, which indicates a timeout.

http://linux.die.net/man/2/select

xaxxon
  • 19,189
  • 5
  • 50
  • 80