Tuesday 15 June 2010

c - sigaction catching SIGALRM -



c - sigaction catching SIGALRM -

my goal create alarm goes off every sec when handled sigaction prints time, each sec new time printed. have loop in middle of code counts random number took out create code more condensed , easier @ because believe problem how i'm using sigaction, because prints multiple times 1 sec need 1 line of output second.

#include <stdio.h> #include <signal.h> #include <time.h> #include <unistd.h> #include <stdlib.h> void alarmprint(int signum); time_t curtime; int main(){ printf("enter ^c end program:\n"); struct sigaction sig; sig.sa_handler = alarmprint; int count; int final; time(&curtime); srandom(curtime); while(1){ time(&curtime); alarm(1); printf("\n"); if(sigaction(sigalrm, &sig, 0) == -1){ printf("error\n"); } } homecoming 0; } void alarmprint(int signum){ printf("current time %s\n", ctime(&curtime)); }

as others have pointed out.

you should move sigaction outside of loop , alarm.

#include <stdio.h> #include <signal.h> #include <time.h> #include <unistd.h> #include <stdlib.h> void alarmprint(int signum); int main(){ int count; int final; printf("enter ^c end program:\n"); signal(sigalrm, alarmprint); alarm(1); while(1) { /* other stuff here */ } homecoming 0; } void alarmprint(int signum){ time_t curtime; time(&curtime); printf("current time %s", ctime(&curtime)); alarm(1); }

you need reset alarm within of alarmprint() function go off in second.

lastly ctime() includes new line, don't need 1 when printing time.

c

No comments:

Post a Comment