Computer Science, asked by hussupoona2807, 1 year ago

Write the program for every sec interrupt to display time in c

Answers

Answered by SPIDEY123
1
A signal to a program interrupts it's execution, and inserts the signal handler in the execution path, making it very exact, if you print something out from the handler, it might even end up in the middle of some text you are printing out from elsewhere.

#include <unistd.h>

#include <signal.h>

 

int alarm_stop = FALSE;

unsigned int alarm_period = 30;

 

void on_alarm(int signal) {

if (alarm_stop) return;

else alarm(alarm_period);

// Insert periodic stuff here.

}

 

int main() {

signal(SIGALRM, on_alarm);

alarm(alarm_period);

for (;;) {

// do your stuff here

}

}

Edit: The example above has an interval that is not exactly 30 seconds, since there are some delays and possible thread pool timing issues that happen before it asks for another 30 seconds, but it is good enough for the majority of use cases. To make it more exact you would store a global time-stamp and skew the alarm()-calls parameter based on time() and that time-stamp.

The time() mainloop way:
More portable, and runs when you have no other work running, making it less disruptive, but requires you to basically redo your logic in an event-driven way.

#include <time.h>

 

int main() {

int program_done = FALSE;

time_t start = time();

while(1){

if (start - time() >= 30) {

start = start + 30;

// insert periodic stuff here

}

// do small pieces of work here, no longer than the timer limit.

// if no work to do, a sleep(1) could be placed here.

if (program_done) break;

}

}


Similar questions