Guest User

Untitled

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