ocaml-containers icon indicating copy to clipboard operation
ocaml-containers copied to clipboard

[CCUnix] add function to call a process with a timeout

Open grayswandyr opened this issue 8 years ago • 5 comments

The subject says it all.

grayswandyr avatar Jul 18 '17 13:07 grayswandyr

That would be useful indeed, but I haven't found a way of doing it without multi-threads. Technical suggestions welcome.

c-cube avatar Jul 20 '17 09:07 c-cube

Could this go into a CCProcess or similar module under containers.threads? It could provide similar functionality to Lwt's https://ocsigen.org/lwt/3.1.0/api/Lwt_process

hcarty avatar Jan 22 '18 17:01 hcarty

@hcarty I think it should be in the unix sub-library anyway, but the problem is I'm not sure how to do it even with threads (Thread.kill doesn't work, and I think it's a bit messy to kill the subprocess while the thread is running).

Maybe we can do sth where we fork manually and setup a ulimit/rlimit, or setup some alarm (Unix.alarm?) before exec'ing the command. Do you know if alarm is preserved by exec?

c-cube avatar Jan 22 '18 17:01 c-cube

I tried this little experiment:

let f () =
  let st = Unix.gettimeofday() in
  let pid = Unix.fork() in
  if pid=0 then (
    Unix.alarm 4;
    Unix.execv "sleep" [| "sleep"; "10" |]
  ) else (
    Unix.waitpid [] pid;
    Printf.printf "done (%.2f)" (Unix.gettimeofday() -. st)
  );;

f();;

and it does print "done" after 4s. So it might work. What do you think?

c-cube avatar Jan 22 '18 17:01 c-cube

That's pretty promising - I didn't realize the signal would persist like that.

It would be nice to have something which doesn't rely on Unix.fork for better Windows compatibility. If I can get some time for it I'll try to work something out with threads and killing the subprocess after its time is up. And capture the subprocess's output if I'm feeling adventurous.

hcarty avatar Jan 22 '18 17:01 hcarty