[fpc-pascal] EControlC exception

Michael Van Canneyt michael at freepascal.org
Wed Feb 6 11:27:45 CET 2008



On Wed, 6 Feb 2008, Guillermo Martínez Jiménez wrote:

> Hi.
> 
> Recently I discovered that Delphi can detect [Ctrl]+C keys using the
> EControlC exception. I was curious so I decided to test it in Linux
> using Free Pascal. The program I wrote:
> _________________________________
> 
> PROGRAM ExControlC;
> (* How to capture [Ctrl+C] in Object Pascal.  *)
> 
> {$mode objfpc}{$H+}
> 
> USES
>   SysUtils;
> 
> VAR
>   Tmp: STRING;
> BEGIN
>   TRY
>     WriteLN ('Press [Enter] or [Ctrl+C].');
>     ReadLN (Tmp);
>     WriteLN ('You pressed [Enter].');
>   EXCEPT
>     ON EControlC DO WriteLN ('You pressed [Ctrl+C].');
>   END;
>   WriteLN ('Have a nice day.');
> END.
> _________________________________
> 
> That's simple. I tested it on Linux but it doesn't worked. It compiles
> and run, but if you press [Ctrl]+C the program exits without the "You
> pressed [Ctrl+C]." message. Is it an issue or a bug? May be it's not
> possible to detect [Ctrl]+C in Linux?

It is not always possible. The shell catches the ctrl-c and kills your
program using a SIGINT signal.

You can catch this signal using a signal handler:

PROGRAM ExControlC;
(* How to capture [Ctrl+C] in Object Pascal.  *)

{$mode objfpc}{$H+}

USES
  SysUtils,baseunix;

procedure term(sig :longint);cdecl;

begin
  Writeln('Interrupt caught');
  Halt;
end;


VAR
 Tmp: STRING;
BEGIN
  fpsignal(SIGINT, at term);
  TRY
    WriteLN ('Press [Enter] or [Ctrl+C].');
    ReadLN (Tmp);
    WriteLN ('You pressed [Enter].');
  EXCEPT
    ON EControlC DO WriteLN ('You pressed [Ctrl+C].');
  END;
  WriteLN ('Have a nice day.');
END.

Should print
gru: >fpc tt.pp
gru: >./tt
Press [Enter] or [Ctrl+C].
Interrupt caught


Michael.

> 
> Guillermo "Ñuño" Martínez
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
> 


More information about the fpc-pascal mailing list