Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

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: 2003-04-16 (19:16)
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:

        /* call C functions */

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 */
        /* call C functions */
        /* 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 Archives:
Bug reports: FAQ:
Beginner's list: