Guest User

Untitled

a guest
Feb 20th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. open Prelude
  2.  
  3. (* adapted from unix.ml *)
  4.  
  5. let try_set_close_on_exec fd =
  6. try Unix.set_close_on_exec fd; true with Invalid_argument _ -> false
  7.  
  8. let open_proc cmd input output toclose =
  9. let cloexec = List.for_all try_set_close_on_exec toclose in
  10. match Unix.fork () with
  11. 0 -> if input <> Unix.stdin then begin Unix.dup2 input Unix.stdin; Unix.close input end;
  12. if output <> Unix.stdout then begin Unix.dup2 output Unix.stdout; Unix.close output end;
  13. if not cloexec then List.iter Unix.close toclose;
  14. begin try Unix.execvp (head cmd) (Array.of_list cmd)
  15. with _ -> exit 127
  16. end
  17. | id -> id
  18.  
  19. let popenWithStdin cmd stdin =
  20. let (in_read, in_write) = Unix.pipe () in
  21. ignore (open_proc cmd stdin in_write [in_read]);
  22. Unix.close in_write;
  23. Unix.close stdin;
  24. in_read
  25.  
  26.  
  27. let rec buildPipeline cmds ifd = match cmds with
  28. | [] -> ifd
  29. | (h::t) -> buildPipeline t (popenWithStdin h ifd)
  30.  
  31. let withPipeline cmds f =
  32. let ifd, ofd = Unix.pipe () in
  33. let ifd = buildPipeline cmds ifd in
  34. let ic, oc = Unix.in_channel_of_descr ifd, Unix.out_channel_of_descr ofd in
  35. finally (fun _ -> maybeE () close_out oc; maybeE () close_in ic)
  36. (f ic) oc
  37.  
  38. let pipeline = [
  39. ["tr"; "[:upper:]"; "[:lower:]"];
  40. ["grep"; "-o"; "ello"];
  41. ]
  42.  
  43. let () =
  44. let ifd, ofd = Unix.pipe () in
  45. let ifd = buildPipeline pipeline ifd in
  46. let oc = Unix.out_channel_of_descr ofd in
  47. output_string oc (readFile "pipeline.ml");
  48. close_out oc;
  49. puts (readAll (Unix.in_channel_of_descr ifd))
  50. (* withPipeline pipeline
  51. (fun ic oc ->
  52. output_string oc "hElLo JeLlo";
  53. close_out oc;
  54. puts (readAll ic)
  55. )*)
Add Comment
Please, Sign In to add comment