forthctrlgforth

how to trap/disable CTRL+C in GFORTH


how to trap/disable CTRL+C in GFORTH ?

I often use common case...endcase statement on key but ctl+c is still possible to user.

I would add a function or something to disable it inside a word like

    : toto
\ do some stuff
\ <<---------- disable ctrl+c here 
key
81 of exitprog endof 
49 of manage1 endof
50 of manage2 endof
\ etc.
endcase
\ <<---------- enable ctrl+c back
;

or more efficient a way to trap it to a specific word execution

\ trap ctrl+c
: exitonctrlc dostuff 0 (bye) ;

I found no solution for that in official documentations 0.7.* version(s)


Solution

  • The current Gforth version throws the code -28 on Ctrl+C.

    So if you want to get a code from key on Ctrl+C, you can just redefine key in your application word list as follows:

    -28 constant key-ctrl-c-ior
    
    : key ( -- x )
      ['] key catch dup key-ctrl-c-ior = if exit then throw
    ;
    

    Now key returns quasi key code -28 if the user presses Ctrl+C.

    If you want to perform some actions on Ctrl+C before trap, you have to just catch your application main word (and don't redefine key), e.g.:

    : main
      ['] main catch
      case ( ior )
        key-ctrl-c-ior of dostuff 0 (bye) endof
        \ ...
      endcase
    ;