Operating system for OpenComputers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.3KB

  1. do
  2. local tTasks,nPid,nTimeout,cPid = {},1,0.25,0 -- table of tasks, next process ID, default event timeout, current PID
  3. function os.spawn(f,n) -- function string -- number -- creates a process from function *f* with name *n*
  4. tTasks[nPid] = {
  5. c=coroutine.create(function()
  6. local rt = {pcall(f)}
  7. if not rt[1] then
  8. syslog(rt[2])
  9. end
  10. computer.pushSignal("process_finished",os.pid(),table.unpack(rt))
  11. end), -- actual coroutine
  12. n=n, -- process name
  13. p=nPid, -- process PID
  14. P=cPid, -- parent PID
  15. t=0, -- CPU time
  16. T=0, -- total uptime
  17. E=nTimeout, -- event timeout
  18. e={} -- environment variables
  19. }
  20. if tTasks[cPid] then
  21. for k,v in pairs(tTasks[cPid].e) do
  22. tTasks[nPid].e[k] = tTasks[nPid].e[k] or v
  23. end
  24. end
  25. nPid = nPid + 1
  26. return nPid - 1
  27. end
  28. function os.kill(pid) -- number -- -- removes process *pid* from the task list
  29. tTasks[pid] = nil
  30. end
  31. function os.pid() -- -- number -- returns the current process' PID
  32. return cPid
  33. end
  34. function os.tasks() -- -- table -- returns a table of process IDs
  35. local rt = {}
  36. for k,v in pairs(tTasks) do
  37. rt[#rt+1] = k
  38. end
  39. return rt
  40. end
  41. function os.taskInfo(pid) -- number -- table -- returns info on process *pid* as a table with name and parent values
  42. pid = pid or os.pid()
  43. if not tTasks[pid] then return false end
  44. return {name=tTasks[pid].n,parent=tTasks[pid].P,cputime=tTasks[pid].t,iotime=tTasks[pid].T,timeout=tTasks[pid].E}
  45. end
  46. function os.sched() -- the actual scheduler function
  47. os.sched = nil
  48. local sTimeout = nTimeout
  49. while #tTasks > 0 do
  50. local tEv = {computer.pullSignal(sTimeout)}
  51. sTimeout = nTimeout
  52. for k,v in pairs(tTasks) do
  53. if coroutine.status(v.c) ~= "dead" then
  54. cPid = k
  55. local sT, sC = os.clock(), computer.uptime()
  56. coroutine.resume(v.c,table.unpack(tEv))
  57. v.t, v.T = v.t + os.clock() - sT, v.T + computer.uptime() - sC
  58. sTimeout=math.min(sTimeout, v.E)
  59. else
  60. tTasks[k] = nil
  61. end
  62. end
  63. end
  64. end
  65. function os.setenv(k,v) -- set's the current process' environment variable *k* to *v*, which is passed to children
  66. if tTasks[cPid] then
  67. tTasks[cPid].e[k] = v
  68. end
  69. end
  70. function os.getenv(k) -- gets a process' *k* environment variable
  71. if tTasks[cPid] then
  72. return tTasks[cPid].e[k]
  73. end
  74. end
  75. function os.setTimeout(n,pid)
  76. assert(type(n) == "number" and n >= 0)
  77. tTasks[pid or cPid].E = n
  78. return true
  79. end
  80. end