Operating system for OpenComputers
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

78 строки
2.0KB

  1. do
  2. local tTasks,nPid,nTimeout,cPid = {},1,0.25,0 -- table of tasks, next process ID, 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. e={} -- environment variables
  16. }
  17. if tTasks[cPid] then
  18. for k,v in pairs(tTasks[cPid].e) do
  19. tTasks[nPid].e[k] = tTasks[nPid].e[k] or v
  20. end
  21. end
  22. nPid = nPid + 1
  23. return nPid - 1
  24. end
  25. function os.kill(pid) -- number -- -- removes process *pid* from the task list
  26. tTasks[pid] = nil
  27. end
  28. function os.pid() -- -- number -- returns the current process' PID
  29. return cPid
  30. end
  31. function os.tasks() -- -- table -- returns a table of process IDs
  32. local rt = {}
  33. for k,v in pairs(tTasks) do
  34. rt[#rt+1] = k
  35. end
  36. return rt
  37. end
  38. function os.taskInfo(pid) -- number -- table -- returns info on process *pid* as a table with name and parent values
  39. pid = pid or os.pid()
  40. if not tTasks[pid] then return false end
  41. return {name=tTasks[pid].n,parent=tTasks[pid].P}
  42. end
  43. function os.sched() -- the actual scheduler function
  44. os.sched = nil
  45. while #tTasks > 0 do
  46. local tEv = {computer.pullSignal(nTimeout)}
  47. for k,v in pairs(tTasks) do
  48. if coroutine.status(v.c) ~= "dead" then
  49. cPid = k
  50. coroutine.resume(v.c,table.unpack(tEv))
  51. else
  52. tTasks[k] = nil
  53. end
  54. end
  55. end
  56. end
  57. function os.setenv(k,v) -- set's the current process' environment variable *k* to *v*, which is passed to children
  58. if tTasks[cPid] then
  59. tTasks[cPid].e[k] = v
  60. end
  61. end
  62. function os.getenv(k) -- gets a process' *k* environment variable
  63. if tTasks[cPid] then
  64. return tTasks[cPid].e[k]
  65. end
  66. end
  67. function os.getTimeout()
  68. return nTimeout
  69. end
  70. function os.setTimeout(n)
  71. if type(n) == "number" and n >= 0 then
  72. nTimeout = n
  73. return true
  74. end
  75. return false
  76. end
  77. end