...
void sighandler(int signum)
{
    fprintf(stderr,"Caught signal %d\n",signum);

    socket_closer();

    exit(0);
}
...
void socket_closer()
{
        pid_t process_id = getpid();
        struct dirent * pDirent;
        DIR           * pDir;
        char command_string[255];
        char buffer[256];
        FILE * curr_file = NULL;



        fprintf(stderr,"%ld\n\n",process_id);

        sprintf(command_string,"/proc/%ld/net",(long)process_id);

        pDir = opendir (command_string);
        if (pDir == NULL)
        {
            fprintf (stderr,"Cannot open directory '%s'\n", command_string);
        }
        else
        {
            while ( NULL != ( pDirent = readdir(pDir)) )
            {
                if (!strcmp(pDirent->d_name,"."))
                { continue; }
                if (!strcmp(pDirent->d_name,".."))
                { continue; }

                fprintf(stderr,"[%s]\n",pDirent->d_name);

                curr_file=fopen(pDirent->d_name,"r");

                if ( curr_file == NULL )
                {
fprintf(stderr,"Could not open in read mode!\n"); // curr_file is always NULL :-(
                     continue;
                }


                fprintf(stderr,"Address of curr_file:%ld\n",(long)curr_file);

                // I need to find the socket number and close it...
                // Just dump the contents of the currently open file for now.
                while ( fgets(buffer, 255, curr_file) != NULL )
                { fprintf(stderr,"%s\n",buffer); }

                fclose(curr_file);
            }

            closedir(pDir);
        }
}
...

This is an excerpt from a study program where I'm trying to learn how to close all open sockets in an arbitrary C program from a signal handler. When a signal is caught and you aren't using global variables to store the socket numbers, you have to get those numbers in order to explicitly close the sockets. I'm concerned about opened files as well, but that will be another function I call from sighandler. I know I can extract the critical socket number information from proc, but how? Just to be clear, Linux will clean up if the function exit is called, but it's too slow taking between 15 seconds to 3 minutes.
_______________________________________________
PLUG mailing list
[email protected]
http://lists.pdxlinux.org/mailman/listinfo/plug

Reply via email to