Browse thread
select (or polling) on in_channel?
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Christoph Bauer <ich@c...> |
| Subject: | Re: [Caml-list] select (or polling) on in_channel? |
Hi,
here is a solution that seems to work. The function Stdinbuf.lines
returns a list of available lines. It works with or without
Unix.select [Unix.stdin] [] [] delay
Christoph Bauer
(* Stdinbuf.ml *)
let () = Unix.set_nonblock Unix.stdin
let buf = ref (String.create 256)
let pos = ref 0
let rec lines stdin =
let len = String.length !buf in
let r =
try Unix.read stdin !buf !pos (len - !pos)
with Unix.Unix_error( Unix.EAGAIN, _ , _ ) -> 0 in
pos := r + !pos;
if !pos >= len then
let s' = String.create (len*2) in
String.blit !buf 0 s' 0 len;
buf := s';
lines stdin
else
try
let e = String.rindex_from !buf !pos '\n' in
let c = String.sub !buf 0 e in
String.blit !buf e !buf 0 (!pos-e);
pos := !pos - e;
StringUtils.split ~sep:'\n' c
with Not_found -> []
(* eof *)
For completeness:
(* stringUtils.ml *)
(* ... * )
let split ?(sep = ' ') ?(empty = false) s =
let rec loop acc i =
let s, idx =
try
let idx = String.rindex_from s i sep in
String.sub s (idx+1) (i-idx), (idx-1)
with Not_found ->
String.sub s 0 (i+1), ~-1
in let acc' =
if empty || s <> "" then s::acc
else acc
in
if idx = ~-1 then acc'
else loop acc' idx
in loop [] (String.length s -1)
--
let () = let rec f a w i j = Printf.printf "%.20f\r" a; let a1 = a *. i /. j in
if w then f a1 false (i +. 2.0) j else f a1 true i (j +. 2.0) in f 2.0 false 2.0 1.0