Reputation: 31
I require some assistance or advice in a C programming task that I received...
The task is that with the alarm(sec)
a signal SIGALRM
needs to be called.
I have to increase a long int number in 1 second and print out on the screen how many times the number was increased in that time. I suspect that it will have to go with the alarm(1);
I have the loop to increase the number ... bit have absolutely no idea on how to stop it after 1 second especially with the signal(SIGALRM,xxx)
Shall I paste in the code that I have ?
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int loop_function() {
int counter = 1;
long int n = 1;
while(n!=0) {
++counter;
n++;
printf("%d: %d\n",counter,n);
}
}
int main() {
loop_function();
}
Upvotes: 0
Views: 1457
Reputation: 1605
Probably, this is what you are looking for.
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void sigalrm_handler(int);
int loop_function();
static int counter = 1;
static long int n = 1;
int main()
{
signal(SIGALRM, sigalrm_handler);
//This will set the alarm for the first time.
//Subsequent alarms will be set from sigalrm_handler() function
alarm(1);
printf("Inside main\n");
while(1)
{
loop_function();
}
return(0);
}
void sigalrm_handler(int sig)
{
printf("inside alarm signal handler\n");
printf("%d: %d\n",counter,n);
//exit(1);
alarm(1);
}
int loop_function()
{
++counter;
n++;
}
Upvotes: 1