[Haskell-beginners] getChar and keyboard reading

Daniel Fischer daniel.is.fischer at web.de
Sun Jan 24 16:06:19 EST 2010


Am Sonntag 24 Januar 2010 21:49:59 schrieb Matthias Güdemann:
> Hi,
>
> I wrote a program which should read the number of key presses in a
> given time. It forks a thread which calls getChar and increases a MVar
> each time getChar suceeds. After a delay (here 2s) the MVar is read,
> its value is printed and the program exits.
>
>
> import Control.Concurrent
>
> increaseEveryPush mVCount = do
>   _ <- getChar
>   inh <- takeMVar mVCount
>   putMVar mVCount (inh + 1)
>   increaseEveryPush mVCount
>
> main = do
>   x <- newMVar 0
>   forkIO (increaseEveryPush x)
>   threadDelay 2000000
>   inh <- takeMVar x
>   putStr $ "\n" ++ (show inh) ++ " times button pushed\n"
>
>
> But this does not work, as getChar does not succeed if there is no EOF
> given (^D).

No, a newline would suffice. But you could set the buffering of stdin to 
NoBuffering.

main = do
  hSetBuffering stdin NoBuffering
  x <- newMVar 0
  forkIO (increaseEveryPush x)
  threadDelay 2000000
  inh <- takeMVar x
  putStr $ "\n" ++ (show inh) ++ " times button pushed\n"


$ ./keyPress
uzfgoigzoruizhuiorhguioegu
26 times button pushed

It probably won't work on Windows, though.

> It normally just exits with 0 as value in the MVar. Is
> there a way toread the keyboard without having to terminate with EOF?
>
> regards,
> Matthias




More information about the Beginners mailing list