views:

387

answers:

2

there is any way to run an infinite cycle that stops only on user input from keyboard without asking every cycle to continue? in a C program (I'm developing a C chat that read the entries with a for(;;) loop and I need to stop it only when the user want to type and send a message) hi all!

+6  A: 

You didn't specify the OS so I will assume some POSIX compliant OS.

You can use select. This can be used to block on a set of file descriptors (in your case, stdin) with a finite timeout or indefinite blocking.

My guess is, since this is a chat program, you would also want to do this on some other file descriptor, like your chat tcp socket. So you can test for input on both with one call.

In case of windows console, you should be able to use GetStdHandle and WaitForSingleObject/WaitForMultipleObjects if select does not work for you.

Moron
it's windows os
frx08
Windows has a POSIX compatibility layer and supports select().
Tyler McHenry
@frx08: If it is windows, is it console? windows gui? you should specify that too.
Moron
it is in console
frx08
In case of windows console, you should be able to use GetStdHandle and WaitForSingleObject.
Moron
+2  A: 

There are a number of ways of doing this in Windows. Assuming you're using VC++, the easiest way is probably to use _kbhit(). If you want to use the Win32 API directly instead, you could call GetNumberOfConsoleInputEvents() and see whether the return is non-zero.

You could also do an overlapped read, and each time through the loop call WaitForSingleObject with a timeout value of 0. The zero wait means it'll return immediately whether there's input or not. The return value will tell you whether you have any data: WAIT_TIMEOUT means no data has been read yet, and WAIT_OBJECT0 means you have some data waiting to be processed.

Jerry Coffin