Version française
Home     About     Download     Resources     Contact us    
Browse thread
commands.getoutput () in ocaml?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Olivier Andrieu <oandrieu@g...>
Subject: Re: [Caml-list] commands.getoutput () in ocaml?
On 8/22/07, Dave Benjamin <dave@ramenlabs.com> wrote:
> On Wed, 22 Aug 2007, Luca de Alfaro wrote:
>
> > I am looking for a quick way to do the equivalent of
> > s = commands.getoutput ("ls " + name + "*")
> > in Ocaml.
>
> I have translated many of the examples from the Perl Cookbook for the
> Process Management and Communication chapter of the OCaml PLEAC. This is
> one of the topics covered.
>
> http://pleac.sourceforge.net/pleac_ocaml/processmanagementetc.html

about this function:

(* Run a command and return its results as a string. *)
let read_process command =
  let buffer_size = 2048 in
  let buffer = Buffer.create buffer_size in
  let string = String.create buffer_size in
  let in_channel = Unix.open_process_in command in
  let chars_read = ref 1 in
  while !chars_read <> 0 do
    chars_read := input in_channel string 0 buffer_size;
    Buffer.add_string buffer (String.sub string 0 !chars_read)
  done;
  close_in in_channel;
  Buffer.contents buffer

you could use Buffer.add_substring instead of add_string, that will
avoid an intermediate copy of the string

... and you should be using Unix.close_process_in, not close_in
otherwise the subprocess will stay as a zombie.

-- 
  Olivier