Guest User

Untitled

a guest
Dec 18th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. defmodule FromPipe do
  2. #
  3. # Use a helper script "from_pipe_release" to
  4. # release/request each line read from the
  5. # named pipe - effectively implementing a
  6. # crude backpressure mechanism
  7. #
  8. @pipe_name "/tmp/testpipe"
  9. @from_pipe_release "./from_pipe_release"
  10. @from_pipe_clean "./from_pipe_clean"
  11.  
  12. # * terminate potential zombie OS process
  13. # * trash potential left over named pipe
  14. #
  15. def clean() do
  16. script_path = Path.expand(@from_pipe_release)
  17. path = Path.expand(@from_pipe_clean)
  18. System.cmd(path, [script_path, @pipe_name])
  19. end
  20.  
  21. # Signal releasing OS process to clean up and terminate
  22. #
  23. def sig_int(os_pid) do
  24. System.cmd("kill", ["-INT", Integer.to_string(os_pid)])
  25. :ok
  26. end
  27.  
  28. # Start the releasing OS process script.
  29. # Monitor in case process terminates
  30. #
  31. def start do
  32. path = Path.expand(@from_pipe_release)
  33. args = [@pipe_name]
  34. port = Port.open({:spawn_executable, path}, [:binary, args: args])
  35. ref = Port.monitor(port)
  36. {port, ref}
  37. end
  38.  
  39. # Demonitor and Close and close port
  40. # Signal OS process to terminate
  41. #
  42. def stop({port, ref}) do
  43. Port.demonitor(ref, [:flush])
  44. info = Port.info(port, :os_pid)
  45. Port.close(port)
  46.  
  47. # interrupt script reading from named pipe
  48. case info do
  49. {:os_pid, os_pid} ->
  50. sig_int(os_pid)
  51.  
  52. _ ->
  53. :ok
  54. end
  55. end
  56.  
  57. # Data Processing Loop
  58. #
  59. def loop({port, ref} = args) do
  60. # i.e. ready for next line
  61. Port.command(port, "ready\n")
  62.  
  63. receive do
  64. {^port, {:data, "quit\n"}} ->
  65. stop(args)
  66.  
  67. {^port, {:data, data}} ->
  68. IO.puts("port data: #{data}")
  69. loop(args)
  70.  
  71. {:DOWN, ^ref, :port, ^port, _reason} ->
  72. # script was terminated
  73. :ok
  74.  
  75. msg ->
  76. IO.puts("other: #{inspect(msg)}")
  77. loop(args)
  78. end
  79. end
  80.  
  81. # Start "listening""
  82. #
  83. def run() do
  84. clean()
  85. loop(start())
  86. end
  87. end
Add Comment
Please, Sign In to add comment