LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 11-17-2005, 04:48 AM   #1
aru_04
LQ Newbie
 
Registered: Nov 2004
Posts: 24

Rep: Reputation: 15
Unhappy how to implement 'press n within 5 secs to terminate..' type of code


greetings everybody!
I was trying to write a piece of code in C (similar to the messages found during bootup in Linux sometimes.)
The program should display a message like-
'Proceeding to phase2...(press 'n' within 5 secs to exit)'
if the user types in 'n' before 5 secs are up, the program should
exit,else after 5 secs, the program should go on to the next phase.
I am trying to use alarm(5) and loop type of mechanism to implement this
but the problem is:
To take an input from the user we have to use input-fns like getchar(),
which block for user-input and if the user doesn't input anything,the
loop continues forever and the program doesn't move forward.
Any ideas how to implement this ,mates?
(forgive me if this proves to be childishly simple though..sometimes,
during programming, your mind really gets blocked misses the little things.
regards,
aru
 
Old 11-17-2005, 05:27 AM   #2
bigearsbilly
Senior Member
 
Registered: Mar 2004
Location: england
Distribution: Mint, Armbian, NetBSD, Puppy, Raspbian
Posts: 3,515

Rep: Reputation: 239Reputation: 239Reputation: 239
HAHA that old chestnut

you will need to play with termios.
tcsetattr tcgetattr.

look up man pages.
here's a shell script (messy) to give you a clue to values to set.
the stty bits are basically the same as what you need for tcsetattr

Code:
#!/bin/ksh


trap cleanup EXIT HUP TERM

save=`stty -g`
count=0

cleanup()
{
    stty $save
    echo '\033c'
}

get_key()
{
     2>/dev/null dd bs=10 count=1
}

ttyset()
{
# if min is zero it won't wait
# if min is 1 it waits for 1 char etc.
#
#
# if it's zero it doesn't wait if it's non-zero
# it returns the minimum amount
     
stty    cs8 -icanon igncr \
             min 1\
             time 0\
             -echo isig -xcase \
             -inpck -opost
}

ESC=


echo '\033c'
echo "\n\nPress a key (q = quit)"
ttyset
while true ;do
    x=`get_key`
    count=`expr $count + 1`
     [ "$x" = q ] && exit
    # [ "$x" = $ESC ] && break

    echo '\033[H' "$count\033[10H\033[1K got"
    print  -n "$x           "|od -c
done
print  -n "$x"|od -c
 
Old 11-17-2005, 08:56 AM   #3
Wim Sturkenboom
Senior Member
 
Registered: Jan 2005
Location: Roodepoort, South Africa
Distribution: Ubuntu 12.04, Antix19.3
Posts: 3,794

Rep: Reputation: 282Reputation: 282Reputation: 282
My solution would be:
Use select and add stdin to the rdfds. Select will timeout if nothing has happened on the filedescriptor, else you can check the input with e.g. read.
To just handle a keypress instead of having to wait for <enter> as well, have a look at cfmakeraw.
 
Old 11-17-2005, 11:02 AM   #4
vivekr
Member
 
Registered: Nov 2005
Location: Coimbatore,India
Distribution: Fedora Core4
Posts: 68

Rep: Reputation: 15
Hai buddy,
I think this piece of code will work.


Code:
#include<stdio.h>
#include<time.h>
#include<conio.h>

void main()
{
	char ch;
	time_t t;
	printf(" Press \'n\' within 5 secs:");
	t=time(NULL);
	while(!kbhit())
               {	
		if(time(NULL)-t>=5)
		{
			printf("\n Provided time expired");
                                               return;   
		}
	}    
	if((ch=getche())=='n')
	{
		printf("Hello"); // do whatever u want
	}
}
I did this using MS Visualstudio-
Good luck

Last edited by vivekr; 11-18-2005 at 01:15 AM.
 
Old 11-17-2005, 01:54 PM   #5
Wim Sturkenboom
Senior Member
 
Registered: Jan 2005
Location: Roodepoort, South Africa
Distribution: Ubuntu 12.04, Antix19.3
Posts: 3,794

Rep: Reputation: 282Reputation: 282Reputation: 282
Quote:
Originally posted by vivekr
[B]Hai buddy,
I think this piece of code will work.
.....
.....
I did this using MS Visualstudio-
Although it's not stated that the code should run under Linux, I assume that that's more than likely the case on this forum.
I could not compile the code on my RH8 box.
1) I could not find conio.h in the include files on my RH8 box (and the compiler complains)
2) man kbhit does not give results on RH8 or Slack10 (and the linker complains as well)
 
Old 11-17-2005, 07:02 PM   #6
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
use select()

You could use select() like :
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/errno.h>

#define SECONDS_2_WAIT 5

int main (int argc, char * argv[]) {

	fd_set set;
	struct timeval timeout;
	int t = 1;
	
	/* Initialize the file descriptor set. */
	FD_ZERO (&set);
	FD_SET (STDIN_FILENO, &set);

	/* Initialize the timeout data structure. */
	timeout.tv_sec = SECONDS_2_WAIT;
	timeout.tv_usec = 0;

	printf("Proceeding to phase2...(press 'n' within 5 secs to exit)\n");

	while(1) {
		/* select returns 0 if timeout, 1 if input available, -1 if error. */
		t = select (FD_SETSIZE, &set, NULL, NULL, &timeout);
		if(t == 1) {
			
			if('n' == getchar()) {
				printf("Exiting, char 'n' was typed...\n");
				return 0;
			}
		
		} else if(t == 0) { /* timeout */
			break;

		} else { /* error */
			printf("select() error: %i\n", errno);
			return 1;
		}
		
	}
	printf("Ok timeout, continue...\n");
	return 0;
}
See more infos at :
http://www.gnu.org/software/libc/man...r-I_002fO.html
 
Old 11-18-2005, 01:17 AM   #7
vivekr
Member
 
Registered: Nov 2005
Location: Coimbatore,India
Distribution: Fedora Core4
Posts: 68

Rep: Reputation: 15
To keefaz,
can u explain about select function please.

Thank you.
 
Old 11-18-2005, 01:44 AM   #8
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
vivekr -

1. The problem with "conio.h" and "kbhit()" is that it's specific to DOS (not even Windows, unless you're in a command prompt).

2. "select()" is an EXTREMELY powerful, EXTREMELY useful Unix call for waiting on the first of any number of possible inputs: for example, a mouse click OR a key press OR a socket read OR a timeout. You can find more here:

a) man 2 select

b) http://linuxgazette.net/issue76/marinov.html
<= THIS IS A *GREAT* LITTLE HOWTO;
AMONG OTHER THINGS, IT DISCUSSES HOW TO DO A "KBHIT()" USING "SELECT()"...
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
text editor for slackware - KDE to type C code kotoko Slackware - Installation 9 04-18-2017 11:11 AM
How can I type ASCII codes in a similar way like the old ALT+<code> way? pujolasdf Linux - Software 0 07-17-2005 03:22 PM
disconnected after x secs: turn this off? grasland Linux - Networking 1 06-29-2004 01:48 AM
What key to press in order to type symbols? windz Linux - General 0 02-10-2004 06:03 AM
Slackware 9 rebooting after 15-20 secs chakotay Slackware 4 03-26-2003 09:00 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:01 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration