So it's just that - sloppy, and honestly stupid. But what I'm going to show you today is the future of terminating programs. And I call it superterminate.
Supertermination is using parallel.waitForAny() to run both the foreground (program) process and a background process at the same time. In the background process, you are checking for something to happen and then if that condition is met, you are ending the background process which kills the foreground (program) process.
More secure - you can disable superterminate selectively whilst completely disabling normal termination, meaning no unintended side effects from terminating.More robust - you can plug superterminate into anything you want, meaning you can customize how it is done. This allows for using it in robust GUIs.More clean - you can run code to prepare the shell to be terminated, so you don't have to deal with what the program leaves behind.Less buggy - you don't have to worry about superterminate killing its parent process - it will only affect things in the parallel and anything below it on a term of scope.
oldPullEvent = os.pullEvent
os.pullEvent = os.pullEventRaw
function backgroundProcess()
while true do
if fs.exists("/.terminate") then
return
else
sleep(0)
end
end
end
function foregroundProcess()
shell.run("/rom/programs/edit")
end
local currentTerm = term.current()
parallel.waitForAny(backgroundProcess, foregroundProcess)
term.redirect(currentTerm)
The above example is very simple. as soon as .terminate exists in the root directory, the program will terminate. One thing to note is how it backs up the term.current(). This is because several APIs such as textutils (wrongfully) override this and can cause issues. Implementing this will fix issues that can occur with these apis. Another thing to note is the overwriting of os.pullEvent. This is done to disable terminating (since users won't need it because of supertermination) increasing security and decreasing issues. However, always back up overwritten objects, in case you need it later.
Now clearly this code is flawed and not production ready, as it will of course always terminate once the file exists, and won't clean up the shell etc. However, making your superterminate robust is out of the scope of this tutorial as it differs depending on its application.
I hope this tutorial has served you well.
If you would like to see some examples of supertermination implementation in operating systems, both OpenTerminalOS and O[OS] have supertermination implemented. I would recommend poking around their code and seeing how it is done.