Signal Handler Not working On my C http Server

Problem: I want my single handler to work as intended and print out "EXITED NICELY" when I press ctrl C. This is a assignment and we must use signal handlers. As you can see I also experimented with sigaction but to the same results.

Current Behaviour: "work" is printing out suggesting the signal handler is working, however it must be getting stuck somewhere because it doesn't cancel the program. Although if I press ctrl c and then send a http request to the server such as curl http:/localhost:port/file.name it will then exit gracefully and print out my desired message. However I would like it to do that without me having to send a request.

Edit through further research. I put a print after and before my accept call. print before will print once and then the accept will just hold it until it receives a connection. So that where the problem is but how do we fix that?

You have to register the signal with sigaction() and without the SA_RESTART flag.

When you register a signal handler with signal(), it will set the SA_RESTART flag. See the glibc manual:

In the GNU C Library, establishing a handler with signal sets all the flags to zero except for SA_RESTART, whose value depends on the settings you have made with siginterrupt. See Interrupted Primitives, to see what this is about.

When SA_RESTART is set, the signal will not interrupt (most) system calls, but it will instead restart them. See the signal man page:

If a signal handler is invoked while a system call or library function call is blocked, then either:

the call is automatically restarted after the signal handler returns; or

the call fails with the error EINTR.

Which of these two behaviors occurs depends on the interface and whether or not the signal handler was established using the SA_RESTART flag (see sigaction(2)).