The goal here was to catch SIGINT to close the server socket on a little socket server. I've tried to use a nested functions to keep the code clean. But...
When I do Ctrl-C (SIGINT, right?), I get Illegal instruction: 4
. After reading this post, I've tried adding -mmacosx-version-min=10.8
to the compile flags since I'm on 10.8. Same error when doing Ctrl-C.
Two questions here: Why do I get `Illegal instruction 4"? How can I close the server socket without using a global variable?
My software:
Mac OSX 10.8.4
GCC 4.2.1
Here's how I'm compiling:
gcc -fnested-functions main.c
Here's the code:
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void register_sigint_handler(int *serverSocket)
{
void sigint_handler(int signal) {
printf("Shutting down...\n");
printf("Server socket was %d\n", *serverSocket);
close(*serverSocket);
exit(0);
}
signal(SIGINT, &sigint_handler);
}
int main(void) {
int serverSocket = 0, guestSocket = 0;
register_sigint_handler(&serverSocket);
serverSocket = socket(PF_INET, SOCK_STREAM, 0);
while (1) {}
close(serverSocket);
return 0;
}