Recent

Author Topic: Trap ctrl-c  (Read 405 times)

Noobie

  • Newbie
  • Posts: 3
Trap ctrl-c
« on: March 21, 2020, 10:48:41 am »
How do I catch ctrl-c event in Linux console application?
If user kill the app by ctrl-c program not closing properly.
Thanks!

PascalDragon

  • Hero Member
  • *****
  • Posts: 1966
  • Compiler Developer
Re: Trap ctrl-c
« Reply #1 on: March 21, 2020, 11:14:40 am »
You need to use either fpSignal or fpSigAction. Here is an example with fpSignal:

Code: Pascal  [Select][+][-]
  1. program tctrlc;
  2.  
  3. uses
  4.   BaseUnix;
  5.  
  6. procedure HandleSigInt(aSignal: LongInt); cdecl;
  7. begin
  8.   Writeln('Ctrl + C used');
  9.   Halt(1);
  10. end;
  11.  
  12. begin
  13.   if FpSignal(SigInt, @HandleSigInt) = signalhandler(SIG_ERR) then begin
  14.     Writeln('Failed to install signal error: ', fpGetErrno);
  15.     Halt(1);
  16.   end;
  17.  
  18.   Writeln('Use Ctrl + C or press ENTER to exit');
  19.   Readln;
  20.   Writeln('Enter used');
  21. end.

You might also want to look at C-based example to learn how to handle signals correctly.

 

TinyPortal © 2005-2018