[omniORB] signals, threads, and C++ exceptions

Favre Benoit ben.favre@wanadoo.fr
Tue Jul 23 10:43:01 2002


You should not try to shutdown the orb in a signal handler. In fact, you 
should not do *anything* in a signal handler since your program is 
multithreaded.
The well-known way to handle SIGINT is to create a thread that will wait for 
a semaphore to be available (sem_wait()). The signal handler should trigger 
the semaphore (sem_post()). Then the thread can do a orb->shutdown(). I could 
not make it work with sigaction() (the single thread handler) but it works 
with signal() (the process wide handler). It will call the signal handler for 
each running thread (but this behaviour is not the same on every 
implementation of the threads), so you have to trigger a flag (or better, a 
semaphore) to prevent more than one thread to handle the signal.
Here are some code snippets :

sem_t semaphore;
pthread_t the_thread;
CORBA::ORB_var orb;

void signal_handler(int unused)
{
    sem_post(&semaphore);
}

void* thread_waiting_for_sigint(void* unused)
{
    sem_wait(&semaphore);
    /* shutdown everything */
    ....
    orb->shutdown(true);
    /* do not exit() here */
    return NULL;
}

int main(int argc,char** argv)
{
    try {
        orb=CORBA::ORB_init(argc,argv,"omniORB3");
        sem_init(&semaphore,0,0);
        pthread_create(&the_thread,NULL,thread_waiting_for_sigint,NULL);
        signal(SIGINT,signal_handler);
        /* do stuff */
        ....
        orb->run();             /* will return after orb->shutdown() */
        orb->destroy();
    } catch (...) {
        cerr<<"an error occured\n";
    }
    return 0;      /* the only reliable exirt point */
}

Cheers, Benoit Favre

Le Lundi 22 Juillet 2002 22:38, vous avez écrit :
> I have a MICO server which needs to be cleanly shut down
> when SIGINT arrives (database connections closed, destructors
> called, etc.).  Since MICO uses threads, I wonder how to do it
> properly -- a simple signal handler in main() does the job,
> but gets called many times for some reason (by each thread?),
> and I need Control-C twice to kill it, so something's fishy.
>
> The pthread book recommends to dedicate a thread to signal
> handling, and mask out the signals on all other threads.
> However, how can we do it with MICO's internal threads?
>
> Ideally, I'd convert a signal to a C++ exception, but I could
> not find any way to do it in g++...  Anybody knows a smart way
> to convert signals to C++ exceptions?
>
> Cheers,
> Alexy
>
> _______________________________________________
> omniORB-list mailing list
> omniORB-list@realvnc.com
> http://www.realvnc.com/mailman/listinfo/omniorb-list