Skip to content

Stdlib.flush hangs when used within signal handler #9794

@stefan-kral

Description

@stefan-kral

I want to flush output channels periodically.

If I use flush stdout in both the signal handler and the regular code, the application hangs.

Here a minimal reproducible example (which I tried on Linux and MacOS using OCaml 4.08 and 4.10):

let n_flush = ref 0;;

let main () =
  Sys.set_signal Sys.sigalrm (Signal_handle (fun _ -> incr n_flush; flush stdout));
  ignore(Unix.setitimer Unix.ITIMER_REAL { it_value = 0.001; it_interval = 0.001 });

  for i = 1 to 100 do
    let s = string_of_int i in
    print_string s;
    flush stdout;
    Unix.sleepf 0.02;
    for j = 1 to String.length s do print_char '\b' done
  done;
  print_string ("n_flush = " ^ string_of_int !n_flush);
  print_endline " ... DONE!";;

main ();;

Note that above time intervals are a lot higher in practise (~1/10s), I pumped them up so that the issue shows more easily.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions