Taking a course in Operating systems and are new to this (and C), I dont really understand a fact stated in my studying material. The program is suppose to pause execution until a kill-command is issued (ctr+c or kill from the terminal) From the beginning the line was:
while (!done);
but it was suggested to change this:
"Using a while loop to repeatedly check the global variable done is not a very efficient use of the CPU. A better way is to change the loop to:
while (pause()) {
if (done) break;
};
"
What does the system do during pause()? If it have to check a global variable every loop can it really do something useful? I'm thinking that pause() probably allow the CPU to pick up other work, but doesn't the checking of the variable ruin that?
The complete code is this if it helps:
#include <stdio.h> // puts(), printf()
#include <signal.h> // SIGFPE, SIGSEGV, SIGINT
#include <stdlib.h> // exit(), EXIT_SUCCESS, EXIT_FAIURE
#include <unistd.h> // getpid(), pause()
#include <stdbool.h> // true, false
sig_atomic_t volatile done = false;
int divide_by_zero() {
int a = 1;
int b = 0;
return a / b;
}
void segfault() {
int *ptr = NULL;
*ptr = 42;
}
void signal_handler(int s) {
switch(s) {
case SIGFPE:
fputs("Caught SIGFPE: arithmetic exception, such as division by zero.\n", stderr);
exit(EXIT_FAILURE);
case SIGSEGV:
fputs("Caught SIGSEGV: segfault.\n", stderr);
exit(EXIT_FAILURE);
break;
case SIGINT:
done = true;
fputs("Caught SIGINT: interactive attention signal, probably a ctrl+c.\n", stderr);
break;
case SIGUSR1:
puts("Hello!");
break;
}
}
int main(void) {
printf("My PID = %ld\n", (long) getpid());
// Install signal handlers.
signal(SIGSEGV, signal_handler);
signal(SIGFPE, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGUSR1, signal_handler);
//divide_by_zero();
//segfault();
// Wait until a signal is delivered.
while(pause()) {
if(done) break;
};
puts("I'm done!");
exit(EXIT_SUCCESS);
}