User:Minozake

From ComputerCraft Wiki
Revision as of 19:30, 12 May 2012 by Minozake (Talk | contribs) (Added safe terminate code)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Miscellaneous thingies

So, I'm using this to post miscellaneous code snippets for other people to use until I find a wiki page for it.

Termination catch for infinite loop daemons

So, let's say you want the source of a program in the form of

while true do
    shell.run("prog", "arg1")
end

It's all fine and good, except for a huge potential problem. If you want to terminate it, you will just restart the program being run in the loop. For computers with the program in their startup, it will require the computer be removed and replaced, and that will destroy the contents saved onto its disk. That's where more complex code comes in handy. The code follows the form:

function doPullEvent ()
    os.pullEventRaw("Terminate")
    print("Terminate caught.  Exiting.")
end

function doRunProg ()
    while true do
        shell.run("gps", "host")
    end
end

parallel.waitForAny(doPullEvent, doRunProg)

An example for use would be a GPS daemon. Unfortunately, a GPS host computer at startup that just has `shell.run("gps", "host")` is prone to failures due to timing problems or thunderstorms since they depend on at least 4 other computers to get up and running properly, and it will also be a problem for entire networks that base their hosting off of 4 main computers. A workaround is to hardcode all of the computers, but that requires manual or more complex auto setups. Running `shell.run("gps", "host")` in a startup infinite loop is a fix, but it also blocks all other operation of the computer, especially if trying to debug. Adding the termination catch so that the script is safe to run on startup is recommended and optimal.

I will leave it as an exercise to the reader to figure out how to make this into a flexible script and make it loadable as an API.