in reply to Re: Parent process finished. How to exit the child process.
in thread Parent process finished. How to exit the child process.

OK, let me explain what I'm trying to do. Being bored, I started writing a old computer game called sokoban today. The simple example looks like this and it runs on Xterm.

XXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXX XX XXXXXXXXXXX XX @ XXXXXXXXXXXX XX@XXXXXXXXXXX sX X XXXXXXXXXXX sX X * X XXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXX

* is a "player" which you manipulete its move by h/k/l/j key and the "player" pushes '@'s through the open space(where no 'X's are)to move them to the locatins marked as 's'. I want to measure the time and display it while the game is going on.

The below is the initial code. $c could be h/k/l/j to move the player('*') to left/up/right/down(vi's key-bind) and whenever these keys are typed, the player gets moved accordingly. Initially, I did it with non-blocking read like this.

while(1){ if($c = Readkey(-1)){ # running/playing game etc. } sleep(1); print $count++; }

however, the time lag caused by sleep command was annoying especially when typing in continuously. The next I did was making sleep time very short, but after a while, CPU fan of my laptop started running and got noisy. At this point, I thought using sleep and ReadKey(-1) in the same loop didn't work well.

So I was wondering how I could put the sleep command and ReadKey to the separate while loops, then I came up with the idea to separate the process for game handling and time measurement. By separating the tasks, time measurement and game handling work independently, and I don't have to use nonblocking read(because halting the looping by blocking read doesn't hurt anything anymore) so that the loop gets active only when keys are pressed which helps my laptop keep cooler.

At this moment, I modified the program based on the 2nd option suggested by spazm and it's working, but if there are any better ways (or right ways), I'd like to know. As you can see, this is not something to handle the system tasks and the measured time is not necessarily very accurate.

Replies are listed 'Best First'.
Re^3: Parent process finished. How to exit the child process.
by rovf (Priest) on May 10, 2010 at 09:32 UTC
    I want to measure the time and display it while the game is going on.
    So you want to display kind of "running stopwatch", updated every second?

    Since sleep(1) is unreliable, you can't use counting. Instead I suggest you use the following approach: You use a high-resolution timer (for example, Time::HiRes), sleep for around 0.1 or 0.2 seconds (of course, the *actual* sleep time will differ from this too a bit), and instead of counting, use time and simply display the actual time.

    The only purpose of using the hires timer instead of the normal sleep is to make the update of the display more smoothly.
    -- 
    Ronald Fischer <ynnor@mm.st>