CurrentProcess.hx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package asys;
  2. import haxe.async.*;
  3. import asys.net.Socket;
  4. import asys.io.*;
  5. #if hl
  6. import hl.Uv;
  7. #elseif eval
  8. import eval.Uv;
  9. #elseif neko
  10. import neko.Uv;
  11. #end
  12. /**
  13. Methods to control the current process and IPC interaction with the parent
  14. process.
  15. **/
  16. class CurrentProcess {
  17. /**
  18. Emitted when a message is received over IPC. `initIpc` must be called first
  19. to initialise the IPC channel.
  20. **/
  21. public static final messageSignal:Signal<IpcMessage> = new ArraySignal();
  22. static var ipc:Socket;
  23. static var ipcOut:IpcSerializer;
  24. static var ipcIn:IpcUnserializer;
  25. /**
  26. Initialise the IPC channel on the given file descriptor `fd`. This should
  27. only be used when the current process was spawned with `Process.spawn` from
  28. another Haxe process. `fd` should correspond to the index of the `Ipc`
  29. entry in `options.stdio`.
  30. **/
  31. public static function initIpc(fd:Int):Void {
  32. if (ipc != null)
  33. throw "IPC already initialised";
  34. ipc = Socket.create();
  35. ipcOut = @:privateAccess new IpcSerializer(ipc);
  36. ipcIn = @:privateAccess new IpcUnserializer(ipc);
  37. ipc.connectFd(true, fd);
  38. ipc.errorSignal.on(err -> trace("IPC error", err));
  39. ipcIn.messageSignal.on(message -> messageSignal.emit(message));
  40. }
  41. /**
  42. Sends a message over IPC. `initIpc` must be called first to initialise the
  43. IPC channel.
  44. **/
  45. public static function send(message:IpcMessage):Void {
  46. if (ipc == null)
  47. throw "IPC not connected";
  48. ipcOut.write(message);
  49. }
  50. public static function initUv():Void {
  51. #if !doc_gen
  52. Uv.init();
  53. #end
  54. }
  55. public static function runUv(?mode:asys.uv.UVRunMode = RunDefault):Bool {
  56. #if doc_gen
  57. return false;
  58. #else
  59. return Uv.run(mode);
  60. #end
  61. }
  62. public static function stopUv():Void {
  63. #if !doc_gen
  64. Uv.stop();
  65. Uv.run(RunDefault);
  66. Uv.close();
  67. #end
  68. }
  69. }