Portál AbcLinuxu, 28. října 2025 13:37
man signal, Google.
void signal_handler(int signal){
// reakcia na prijatie signalu
// man 7 signal, pre popis
fprintf(LOG_FILE, "%s INFO: catch signal: \"%s\"\n", time_s(), strsignal(signal));
switch (signal){
case SIGHUP:{
break;
}
case SIGUSR1:{
break;
}
case SIGUSR2:{
break;
}
case SIGPIPE:{
break;
}
case SIGINT: // Interrupt from keyboard
case SIGQUIT: // Quit from keyboard
case SIGKILL: // Kill signal
case SIGTERM:{ // Termination signal
exit(1);
}
case SIGALRM:{
break;
}
}
}
//------------------------------------------------------------------------------------
// zoznam signalov ktore treba po spusteni regnut
// pri registracii prechadzam pole cyklom for a ta nula je detekovana ako koniec pola
const char SIGNAL[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGQUIT, SIGKILL, SIGTERM, SIGPIPE, SIGALRM, 0};
//------------------------------------------------------------------------------------
// registruj signali a alarm
{
char i;
for(i=0; SIGNAL[i]; i++){
signal(SIGNAL[i], signal_handler);
fprintf(LOG_FILE, "%s INFO: Registering signal: %s\n", time_s(),strsignal(SIGNAL[i])); }
}
// FIXME: tu sa caka na prijatie nejakeho
while(1) pause();
fprintf() v handleru signálu není IMHO příliš šťastný nápad, dokonce i dokumentace k libc se o tom zmiňuje:
This case arises when you do I/O using streams. Suppose that the signal handler prints a message with `fprintf'. Suppose that the program was in the middle of an `fprintf' call using the same stream when the signal was delivered. Both the signal handler's message and the program's data could be corrupted, because both calls operate on the same data structure--the stream itself.
fprintf() v normálním toku programu a fprintf() v handleru.
Okrem ineho handler definovany pomocou sigaction moze poskytnut viac informacii. Vid man sigaction
funkcia signal ma nejake nevyhody (ako napr. ze sa musi funkcia zavolat vzdy, pred tym ked chceme signal zachytit - po chyteni teda znovu, ak sa ma znovu chytit)Pokud vím, tak to neplatí všude: /* NOTE some versions of UNIX will reset signal to default after each call. So for portability reset signal each time */
signal nebrat. Úkol bude kontrolován na Linuxu, FreeBSD a SunOS.
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.