1

My question is just what the title says (for Unix/Linux only). I assume that user calls to std::raise and std::abort are always executed in the same thread that made the call, but, I have some questions about asynchronous and kernel routines sending signals...

  • If I send a signal from command line to a thread pid, will the thread treat the signal or it will be treated by the main thread depending on which signal has been sent?
  • If malloc detects some heap corruption, will the signal be sent to the main thread or will be executed as well in the thread that called malloc? The same questions applies to bugs generating SIGFPEs or SIGSEGVs.
  • There are signal that are always treated by the main thread regardless which thread causes it, or to which pid was sent to?
  • Which other situations are worth mention in multithread contexts?
ABu
  • 10,423
  • 6
  • 52
  • 103
  • There is no "_main thread_". - All threads are born equal. – Ted Lyngmo Mar 13 '20 at 13:50
  • 1
    There's also no _root_ thread. Does [this](https://stackoverflow.com/a/2700597/7582247) help? – Ted Lyngmo Mar 13 '20 at 14:00
  • 1
    @TedLyngmo The main thread is generally known as the thread that is executing the `main` function. Everyone understand that. Also, the OS knows perfectly the thread that identifies the process. – ABu Mar 13 '20 at 14:03
  • If it's the thread that executes the `main()` function that you mean, it should be clearly stated. I though you meant a thread with some special attribute. C++ does not know what processes are but Posix threads may have some of that built in. – Ted Lyngmo Mar 13 '20 at 14:17

1 Answers1

2

The main() thread is not special. It receives signals like any other thread.

When a signal is generated "asynchronously" for a process or process group (e.g., by kill or a Ctrl-C at the terminal), the implementation may choose any thread for delivery.

The thread executing main() is no different from any other thread in the process. If you want to control which thread receives the signal, you must block signal delivery in all but one thread, or block and call sigwait from your desired thread.

When a signal is generated "synchronously" within a thread (as by raise, abort, a segmentation fault, etc.) or is targeted at a specific thread (as by pthread_kill), then that thread, and only that thread, will get the signal. If that thread is blocking the signal, then the signal is held pending until unblocked or accepted.

Two very good sources here are the comprehensive but comparatively dense POSIX treatment and the pleasantly accessible GNU libc treatment of UNIX signals. Both are oriented for C rather than C++, however.

pilcrow
  • 56,591
  • 13
  • 94
  • 135