klisp

an open source interpreter for the Kernel Programming Language.
git clone http://git.hanabi.in/repos/klisp.git
Log | Files | Refs | README

ffi-signal.k (1920B)


      1 ;;
      2 ;; Dynamic FFI example.
      3 ;; Signal handling and interpreter extension implemented in C.
      4 ;;
      5 ;; usage:
      6 ;;    .../src$ make posix USE_LIBFFI=1
      7 ;;           $ cd examples
      8 ;;           $ make -f ffi-signal.makefile
      9 ;;           $ ../klisp ffi-signal.k
     10 ;;
     11 ;; files:
     12 ;;  ffi-signal.so ......... interpreter extension compiled to a DLL
     13 ;;  ffi-signal.k .......... example of client code
     14 ;;  ffi-signal.c  ......... C source of the extension
     15 ;;  ffi-signal.makefile ... build script
     16 ;;
     17 
     18 ;; (ffi-klisp-state) returns a value which encodes pointer
     19 ;; to the interpreter global state (klisp_State *).
     20 ;;
     21 ;; The following code loads the dynamic library ffi-signal.so
     22 ;; and passes the klisp_State pointer to the initialization
     23 ;; function kinit_signal_example(). Having access to the
     24 ;; internal interpreter structures, the initialization function
     25 ;; adds new bindings to the current dynamic environment.
     26 ;;
     27 ((ffi-make-applicative
     28   (ffi-load-library "./ffi-signal.so")
     29     "kinit_signal_example"
     30     (ffi-make-call-interface
     31       "FFI_DEFAULT_ABI" "void" (list "pointer")))
     32  (ffi-klisp-state))
     33 
     34 ;; The dynamic environment now contains two new bindings:
     35 ;;
     36 ;;   (install-signal-handler SIGNAME) installs handler for
     37 ;;   the signal named SIGNAME (e.g. "SIGINT"). Whenever
     38 ;;   a signal arrives, the handler writes a byte into
     39 ;;   an internal pipe.
     40 ;;
     41 ;;   (open-signal-port) opens the read-end of the internal pipe
     42 ;;   as a binary input port.
     43 ;;
     44 ;; The following code demonstrates the signal handling (it is not
     45 ;; possible to install arbitrary klisp procedure as a signal handler,
     46 ;; because the interpreter is not reentrant).
     47 ;;
     48 (install-signal-handler "SIGINT")
     49 ($define! signal-port (open-signal-port))
     50 (display "Installed signal handler for SIGINT. Press Ctrl-C to continue...")
     51 (read-u8 signal-port)
     52 (newline)
     53 (display "Signal detected. Press Ctrl-C again...")
     54 (read-u8 signal-port)
     55 (newline)
     56 (display "Done.")
     57 (newline)
     58