Advertisement
Guest User

Untitled

a guest
Dec 14th, 2016
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. non Lwt version:
  2.  
  3. let () =
  4. let parent_pid = Unix.getpid () in
  5. Printf.sprintf "Parent pid:%d" parent_pid |> print_endline;
  6. let some_func () =
  7. Printf.sprintf "Process: %d" (Unix.getpid ())
  8. |> print_endline
  9. in
  10. let marshaled = Marshal.to_bytes some_func [Marshal.Closures] in
  11. let (read, write) = Unix.pipe () in
  12. let pid = Unix.fork () in
  13. (* Child *)
  14. if pid = 0 then begin
  15. let in_chan = Unix.in_channel_of_descr read in
  16. let func : unit -> unit = Marshal.from_channel in_chan in
  17. func ()
  18. end
  19. else begin
  20. Unix.write write marshaled 0 (Bytes.length marshaled) |> ignore;
  21. some_func ();
  22. exit 0
  23. end
  24.  
  25. prints:
  26.  
  27. Parent pid:3760
  28. Process: 3760
  29. Process: 3761
  30.  
  31.  
  32. Lwt version:
  33.  
  34. let program =
  35. let parent_pid = Unix.getpid () in
  36.  
  37. Printf.sprintf "Parent pid:%d" parent_pid
  38. |> Lwt_io.printl
  39. |> Lwt.ignore_result;
  40.  
  41. let some_func () =
  42. Printf.sprintf "Process: %d" (Unix.getpid ())
  43. |> Lwt_io.printl
  44. in
  45. let marshaled = Marshal.to_bytes some_func [Marshal.Closures] in
  46. let (read, write) = Lwt_unix.pipe () in
  47. let pid = Lwt_unix.fork () in
  48.  
  49. (if pid = 0 then begin
  50. let in_chan = Unix.in_channel_of_descr (Lwt_unix.unix_file_descr read) in
  51. let func : unit -> unit Lwt.t = Marshal.from_channel in_chan in
  52. func ()
  53. end
  54. else begin
  55. Lwt_unix.write write marshaled 0 (Bytes.length marshaled)
  56. |> Lwt.ignore_result
  57. |> some_func
  58. |> Lwt.ignore_result;
  59. exit 0
  60. end)
  61.  
  62. let () = Lwt_main.run program
  63.  
  64. Parent pid:3648
  65. Process: 3648
  66. Parent pid:3648
  67. Process: 3649
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement