C
Standard C's sleep() only provides one-second resolution, so the POSIX usleep() function is used here. (POSIX is not needed for the actual signal handling part.)
#include <stdio.h>
#include <stdlib.h> // for exit()
#include <signal.h>
#include <time.h> // for clock()
#include <unistd.h> // for POSIX usleep()
volatile sig_atomic_t gotint = 0;
void handleSigint() {
/*
* Signal safety: It is not safe to call clock(), printf(),
* or exit() inside a signal handler. Instead, we set a flag.
*/
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d
", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds
", td);
return 0;
}
- Output:
1 2 3 Program has run for 1.953 seconds
copyright
https://rosettacode.org/wiki/Handle_a_signal#C
### other signal
void __sigroutine( int p_iSigNum )
{
switch( p_iSigNum )
{
case SIGHUP:
case SIGINT:
case SIGQUIT:
case SIGTERM:
_bStop = true;
printf("recv signal %d
", p_iSigNum);
break;
default:
break;
}
}
bool __init_capture()
{
if( SIG_ERR == signal( SIGHUP, __sigroutine ) )
{
printf("signal SIGHUP failed
");
return false;
}
if( SIG_ERR == signal( SIGINT, __sigroutine ) )
{
printf("signal SIGINT failed
");
return false;
}
if( SIG_ERR == signal( SIGQUIT, __sigroutine ) )
{
printf("signal SIGQUIT failed
");
return false;
}
if( SIG_ERR == signal( SIGTERM, __sigroutine ) )
{
printf("signal SIGTERM failed
");
return false;
}
return true;
}