Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] OCaml signal handlers (Sys.signal) and C code
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] OCaml signal handlers (Sys.signal) and C code
> I've noticed that a callback registered using Sys.signal function for
> the Sys.sigalrm signal isn't called while executing external C code.
> 
> The execution is delayed until the C code execution is over.
> 
> Is there any way to avoid this behaviour? (Actually the only solution I
> see is to modify the C code so that handler is registered there, but I'm
> working with an external library which is not under my own control)
> 
> Is this an intended behaviour or a bug?

Very much intended behavior.  OCaml signal handlers can execute
arbitrary Caml code, including heap allocations and garbage
collections.  If they could be invoked at any time, e.g. in the middle
of a garbage collection, disaster would ensue.

However, there is one workaround for long-running pieces of C code
that do not access the Caml heap: in the Caml/C stub code, wrap the
call to the C function as follows:

        enter_blocking_section();
        /* call C functions */
        leave_blocking_section();

In the "blocking section" that is bracketed by the calls to
enter_blocking_section() and leave_blocking_section(), signals will be
honored immediately.  However, the C code executed inside the blocking
section *must not* heap-allocate nor access the Caml heap in any way.
In practice, this means that all conversions between Caml and C data
structures must be done outside the blocking section:

        /* extract arguments from Caml data, copying them to stack-allocated
           blocks or malloc()-ed blocks */
        enter_blocking_section();
        /* call C functions */
        leave_blocking_section();
        /* convert C results to Caml data */

For examples of use, you can look at the C stub codes in e.g. otherlibs/unix
in the OCaml distribution.

Hope this answers your question.

- Xavier Leroy

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners