bmalhi bmalhi - 4 months ago 16
C Question

How to program control+C signal in C language to pause and unpause the output?

I am new to programming in C also less knowledge working with control signals. Below is my program in which I am trying to

pause
and
unpause
my output running inside the while loop. So far I am able to
Pause
the output by pressing CTRL+C but I am required to
unpause
the output again by pressing CTRL+C which I don't know how to do so. My question is how to
Unpause
my output again by pressing CTRL+C keys. Also I am using Spinlock to suspend the output until CTRL+C is not pressed again which will resume the program to finish displaying output. This program utilizes sleep function to output to the terminal every second. Any advice would be highly appreciated.

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>

void f(int); //handler

int main( int ac, char* av[] )
{

if(ac == 1)
{
printf("No argument provided");
exit(1);
}
int i = atoi(av[1]);
printf("This is argument av: %i ", i);
printf("\n");

signal( SIGINT, f); // install the handler

int k = 0;
while(k != i)
{
printf("help \n");
sleep(1);
k++;
}

return 0;

}
void f(int signum)
{
while(signum)
{
int lock =0;
if(lock == 1)
continue;
}
}

Answer

Some unices reset the signal handling to the defaults after the call, you have to reset it.

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>

static int lock;

void f(int);

int main(int ac, char *av[])
{

  if (ac == 1) {
    printf("No argument provided");
    exit(1);
  }

  int i = atoi(av[1]);
  printf("This is argument av: %i \n", i);
  signal(SIGINT, f);
  int k = 0;
  while (k != i) {
    printf("help %d \n", k);
    while (lock == 1) {
      puts("Sleeping, waiting for signal");
      sleep(1);
    }
    sleep(1);
    k++;
  }
  return 0;
}

void f(int signum)
{
  signal(SIGINT, f);
  printf("Signal raised %d\n", signum);
  if (lock == 1) {
    lock = 0;
  } else {
    lock = 1;
  }
}