Segmentation fault handling

The default action for things like SIGSEGV is to terminate your process but as you’ve installed a handler for it, it’ll call your handler overriding the default behavior. But the problem is segfaulting instruction may be retried after your handler finishes and if you haven’t taken measures to fix the first seg fault, the retried … Read more

POSIX threads and signals

What’s the best way to control which thread a signal is delivered to? As @zoli2k indicated, explicitly nominating a single thread to handle all signals you want handled (or a set of threads each with specific signal responsibilities), is a good technique. What is the best way to tell another thread (that might actually be … Read more

Calling pthread_cond_signal without locking mutex

If you do not lock the mutex in the codepath that changes the condition and signals, you can lose wakeups. Consider this pair of processes: Process A: pthread_mutex_lock(&mutex); while (condition == FALSE) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); Process B (incorrect): condition = TRUE; pthread_cond_signal(&cond); Then consider this possible interleaving of instructions, where condition starts out as FALSE: … Read more

How to capture Control+D signal?

As others have already said, to handle Control+D, handle “end of file”s. Control+D is a piece of communication between the user and the pseudo-file that you see as stdin. It does not mean specifically “end of file”, but more generally “flush the input I typed so far”. Flushing means that any read() call on stdin … Read more

Catch Ctrl-C in C

With a signal handler. Here is a simple example flipping a bool used in main(): #include <signal.h> static volatile int keepRunning = 1; void intHandler(int dummy) { keepRunning = 0; } // … int main(void) { signal(SIGINT, intHandler); while (keepRunning) { // … Edit in June 2017: To whom it may concern, particularly those with … Read more