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
...
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.