Advertisement
Guest User

Simultaneous reading of N pipes

a guest
Nov 10th, 2015
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.86 KB | None | 0 0
  1. let read_descriptors l =
  2.   let buffer_map =
  3.     List.map
  4.       (fun fd ->
  5.     Unix.set_nonblock fd;
  6.     fd,Buffer.create 32) l in
  7.   let data = String.create 1024 in
  8.   let append fd len =
  9.     let chunk =
  10.       String.sub data 0 len in
  11.     let buf =
  12.       List.assoc fd buffer_map in
  13.     if Buffer.length buf + len < Sys.max_string_length then
  14.       Buffer.add_string buf chunk
  15.   in
  16.   let rec read l =
  17.     if l <> [] then
  18.       let (rl,_,_) = Unix.select l [] [] 0.1 in
  19.       let ready =
  20.     List.fold_left
  21.       (fun acc fd ->
  22.         let n = Unix.read fd data 0 1024 in
  23.         if n = 0 then
  24.           begin
  25.         Unix.close fd;
  26.         fd::acc
  27.           end
  28.         else
  29.           begin
  30.         append fd n;
  31.         acc
  32.           end) [] rl
  33.       in
  34.       read (List.filter (fun fd -> not (List.mem fd ready)) l)
  35.     else ()
  36.   in read l;
  37.   List.map
  38.     (fun (_,b) -> Buffer.contents b) buffer_map
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement