0

I am trying to understand threads and signal handling . Please help me understand what difference does it make if I call the signal inside main or the function I am using to create a thread ?

# include <iostream>
# include <cstdlib>
# include <pthread.h>
# include <string.h>
# include <csignal>
using namespace std;
void signalHandler( int signum )
{
    cout <<"\n>> Interrupt signal (" << signum << ") received.";
    cout <<"\n>> Release all the resources.";
    cout <<"\n>> Going down.\n"; 

    // cleanup and close up stuff here  
    // terminate program  
    exit(signum);  

}

void *ShellThread(void *threadid)
{
    //signal(SIGINT, signalHandler);  // 1) signal inside the thread function
    string InputToShell;
    while(1)
    {
        cout<<"\n>> ";
        getline(cin, InputToShell);
        cout<<"Input received"<<InputToShell;
    }

    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
    signal(SIGINT, signalHandler);  // 2) Signal inside the main function
    pthread_t MainShell;
    int rc;

    rc = pthread_create(&MainShell, NULL, ShellThread, (void *)1);

    if(rc)
    {
        cout<<"Unable to create thread";
    }
    pthread_exit(NULL); 
    return 0;
}
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • There's things like [`pthread_sigmask(), sigprocmask`](http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_sigmask.html), though that stuff is OS dependent. – πάντα ῥεῖ May 06 '15 at 19:04
  • http://stackoverflow.com/questions/5282099/signal-handling-in-pthreads http://stackoverflow.com/questions/2575106/posix-threads-and-signals – Ami Tavory May 06 '15 at 19:05
  • My vague understanding, also, is that signal-handlers are thread specific. I honestly don't remember if a signal raised by a thread will be caught by another thread, or if the thread that raised it (if *it* does not have a signal-handler itself) will treat it as an "uncaught signal." I'd experiment by putting some trace-messages in various places to see if you can piece-together what happens on *your* system. – Mike Robinson May 06 '15 at 19:09
  • Why aren't you using C++ threads? There is a standard for that... – Klemens Morgenstern May 06 '15 at 22:03

0 Answers0