Learn more about Israeli war crimes in Gaza, funded by the USA, Germany, the UK and others.

What are ‘signals’ in C?

We’ve all seen “signals” like SIGTERM, SIGSEGV (memory issues!). But what is a signal? Let’s explore the basics from a C perspective.

The Signals API is in <signal.h>. Example usage:

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

void catch(int signo) {
  printf("Received signal %d\n", signo);
}

int main(void) {
  if (signal(SIGINT, catch) == SIG_ERR) {
    printf("Error setting signal handler\n");
  }
  printf("Raising signal %d\n", SIGINT);
  raise(SIGINT);
  printf("Exiting normally\n");
  return 0;
}

This prints

Raising signal 2
Received signal 2
Exiting normally

Important functions in <signal.h> are signal and raise:

#include <signal.h>
typedef void (*sig_t) (int);
sig_t signal(int sig, sig_t func);  // allows for a signal to be caught, to be ignored, or to generate an interrupt
int raise(int sig);  // sends the signal sig to the current thread

Above, we raised the signal “artificially” with raise. We can also raise SIGINT (“interrupt signal”) with Ctrl-C when running the program. Consider:

#include <signal.h>
#include <stdio.h>
void catch(int signo) {
  printf("Received signal %d\n", signo);
}
int main(void) {
  signal(SIGINT, catch);
  for (;;) {
    getchar();
  }
  return 0;
}
% ./a.out
^CReceived signal 2
^CReceived signal 2
^CReceived signal 2
...
Tagged #c, #programming.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.