Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created April 19, 2018 17:33
Show Gist options
  • Save jtpaasch/b1a2617ea47365025074aba38180e292 to your computer and use it in GitHub Desktop.
Save jtpaasch/b1a2617ea47365025074aba38180e292 to your computer and use it in GitHub Desktop.
Simple process runner (Ocaml)
(** Compile with:
[ocamlc -c simpleproc.ml]
[ocamlc -o simpleproc.byte unix.cmo simpleproc.cmo]
Run it:
[./simpleproc.byte "ls -la"]
*)
module Buff = struct
let create = Buffer.create 32
let dump b = Buffer.contents b
let read_all b c =
try
while true do
Buffer.add_channel b c 1
done
with End_of_file -> ()
end
module Proc = struct
let popen = Unix.open_process_full
let pclose = Unix.close_process_full
let int_of_status s =
match s with
| Unix.WEXITED r -> r
| Unix.WSIGNALED r -> r
| Unix.WSTOPPED r -> r
end
module Cmd = struct
let proc cmd env out_buf err_buf =
let out_ch, in_ch, err_ch = Proc.popen cmd env in
ignore (Buff.read_all out_buf out_ch);
ignore (Buff.read_all err_buf err_ch);
let s = Proc.pclose (out_ch, in_ch, err_ch) in
let c = Proc.int_of_status s in
(c, Buff.dump out_buf, Buff.dump err_buf)
end
let main () =
let cmd = Sys.argv.(1) in
let env = [|"foo=bar"|] in
let out_buf = Buffer.create 32 and
err_buf = Buffer.create 32 in
let exit_code, out, err = Cmd.proc cmd env out_buf err_buf in
print_endline "------ stdout";
print_endline out;
print_endline "------ stderr";
print_endline err;
print_endline "------ exit code";
print_endline (string_of_int exit_code)
let () = Unix.handle_unix_error main ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment