[PLUG] Sockets and premature exit C.

michael michael at robinson-west.com
Tue Dec 5 18:46:01 UTC 2017


I"m trying to find out how to close sockets with a signal handler 
function in C without having the socket numbers.

...
#include <signal.h>

void sighandler(int);

void socket_closer(void);

void sighandler(int signum)
{
     socket_closer(); // Close any open sockets...
}

int main(int argc,char * argv)
{
     signal(SIGABRT,sighandler);
     signal(SIGFPE,sighandler);
     signal(SIGILL,sighandler);
     signal(SIGINT,sighandler);
     signal(SIGSEGV,sighandler);
     signal(SIGTERM,sighandler);
        ...
`
     // Open some UNIX, TCP, RAW, or UDP sockets and enter an infinite 
while loop, no closing.
        ...

     // Main never exits normally and this is required.
}

void socket_closer(void)
{
     // Need to get the name of socket ???.
     close(???);

     exit(0);
}

I need to know how to write socket_closer.

Note that the signal handler function does not have any of the socket 
numbers and I cannot store them in global variables.
I should close all filehandles too on signal, but sockets first.  I'm 
trying to use opendir in socket_closer to open
/proc/net/udp, /proc/net/tcp, /proc/net/unix, and /proc/net/raw, but I 
can't.  Is there a process specific proc directory
that I can open?  Specifically, I want the proc entries from the current 
process.  I need immediate socket cleanup or else
I'd leave the program as-is and wait for the stale sockets to be closed 
by Linux.  I think it takes between 15 seconds and
three minutes for Linux to clean up the stale sockets.  That is a LOT of 
time, too long to wait in fact.  I'm looking for
a way to catch any signal that the program is exiting and clean up the 
sockets even though I don't have the socket numbers.


More information about the PLUG mailing list