Reputation: 65
My goal is to make an alarm that goes off every second so that when it is handled by sigaction it prints the time, so each second the new time is printed. I have a loop in the middle of this code that counts to a random number but I took that out to make this code more condensed and easier to look at because I believe the problem is with how I'm using sigaction, because it prints multiple times for one second but I just need one line of output for this 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 to end the 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");
}
}
return 0;
}
void alarmPrint(int signum){
printf("current time is %s\n", ctime(&curtime));
}
Upvotes: 2
Views: 3967
Reputation: 2280
As others have pointed out.
You should move your sigaction outside of the loop and also the 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 to end the program:\n");
signal(SIGALRM, alarmPrint);
alarm(1);
while(1) {
/* do other stuff here */
}
return 0;
}
void alarmPrint(int signum){
time_t curtime;
time(&curtime);
printf("current time is %s", ctime(&curtime));
alarm(1);
}
You also need to reset the alarm inside of your alarmPrint()
function so it will go off in another second.
Lastly ctime()
already includes a new line, so you don't need one when printing the time.
Upvotes: 2