I'm writing a program that counts down from a user desired number. it should pause when ctrl-c is pressed and terminated when ctrl-\ is pressed. I cant seem to get it to pause or countdown. Im new to using signals so i may have done it incorectly.
Code:
#include <stdbool.h>
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
//global variable
bool cont = true;
//signal handling function
void sigHandler(int signal)
{
if(signal == SIGINT)
{
printf("pausing");
cont = false;
}
else
{
cont = false;
}
}
int main(int argc, const char * argv[])
{
// install the handler
signal( SIGINT, sigHandler);
//create terminal interface with termio
struct termios oldTerm;
struct termios newTerm;
//Get the attributes of the terminal
tcgetattr(0, &oldTerm);
//If wrong number of arguments
if(argc != 2)
{
printf("Wrong number of arguments. ");
}
else
{
printf("Initiating Countdown.\n");
//get the Number from argv
int startNum = atoi(argv[1]);
//printf("%d", startNum);
printf("\n");
newTerm.c_iflag &= ~IXOFF;
//set terminal attributes to take effect immediatly
tcsetattr(1, TCSANOW, &newTerm);
while(cont)
{
printf("%d", startNum);
fflush(stdout);
printf("\n");
sleep(1);
}
}
tcsetattr(1,TCSAFLUSH,&oldTerm);
return 0;
}
this is my original code im now modifying to use signals.
Code:
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char * argv[])
{
//create terminal interface with termio
struct termios oldTerm;
struct termios newTerm;
//Get the attributes of the terminal
tcgetattr(0, &oldTerm);
//If wrong number of arguments
if(argc != 2)
{
printf("Wrong number of arguments. ");
}
else
{
printf("Initiating Countdown.\n");
//get the Number from argv
int startNum = atoi(argv[1]);
//printf("%d", startNum);
printf("\n");
newTerm.c_iflag &= ~IXOFF;
//Set P to pause countdown
newTerm.c_cc[VSTOP] = 'p';
//set U to resume countdown
newTerm.c_cc[VSTART] = 'u';
//set terminal attributes to take effect immediatly
tcsetattr(1, TCSANOW, &newTerm);
//create buffer for int to char conversion
//char numToWord[25];
//setvbuf(stdout, (char *)NULL, _IONBF, 0);
for(; startNum > 0; startNum--)
{
//sprintf(numToWord, "%d", startNum);
printf("%d", startNum);
fflush(stdout);
printf("\n");
sleep(1);
}
}
tcsetattr(1,TCSAFLUSH,&oldTerm);
return 0;
}