How to know the signal delivered to thread - multithreading

I have a ARM based embedded system running 2.6.33.
A main process-A creates another process-B. Both are aplication process with Real time RR policy. This proc-B creates few threads with pthread_create(). I guess one of the thread is doing some wrong and the process is killed.
On using wait() in process-A i get status 1 returned (NORMAL) as shown below.
I want to know how to get which signal has been delivered to which thread inside
process-B.
waitpid(-1, &status, WUNTRACED | WCONTINUED)
and
if (WIFEXITED(status))
printf("Process %d terminated normally, status %d\n", pid,WEXITSTATUS(status));
Followed the link but got the same status as 1.
http://www.cs.cf.ac.uk/Dave/C/node32.html#SECTION003240000000000000000
Is there any other ways to find out the correct exit status of all threads and signal if any are sent to these threads ?

Ok, firstly, you should know that multithreading and signalling don't mix very well! This is in large reason due to the fact that signals are delivered to a PID; an MT app has 1 PID but multiple threads; which thread will 'get' / handle the signal?
Thus, the 'usual' strategy is to block all signal in all threads except one thread - a dedicated synchronous 'signal handler' thread (it typically issues the blocking sigwait(2); the return value is the signal that just arrived!).
Here's a (simplistic) app to demo mixing threads and signalling.
Second, to understand some detail about how/why a process died - technically, received a signal - use sigaction(2) with the SA_SIGINFO flag. The signal handler signature now is:
void func(int signo, siginfo_t *info, void *context)
The struct siginfo_t will give you all the detail you need about how/why this process received this signal! Ref: sigaction(2) man page.
Of course using this approach does mean that you use sigaction instead of sigwait.. async vs sync handling.
HTH.

Related

Linux: Real-Time Signals

I am testing different scenarios with real-time signals and unable to found the meaning of every signal such as SIGRTMIN+1 and SIGRTMIN+13.
I am able to send and receive the signals but trying to understand the meaning of all the SIGRTMIN+n signals. For example, I send number of Signals based on my program and one of them is killing a process:
/* The child process executes this function. */
void
child_function (void)
{
/* Perform initialization. */
printf ("I'm here!!! My pid is %d.\n", (int) getpid ());
/* Let parent know you’re done. */
kill (getppid (), SIGUSR1);
/* Continue with execution. */
puts ("Bye, now....");
exit (0);
}
I want to understand these SIGRTMIN+13, how does it work if I pass this to pass to kill a process forcefully.
real-time signals are designed to be used for application-defined purposes(it's up to you to give them a meaning),they have the advantage to be queued and accompanied with data which is not possible with standard signals, to use them effectively they are sent using sigqueue() "not kill()", and handled by sigaction() "not signal()".
I can really recommend reading this manual page. SIGRTMIN defines the lowest number you can choose for a user defined real time signal. By default, any program should behave undefined for this signal if you have not yet implemented the signal handler.

How to differentiate alarm signal of different threads?

I got to implement user level thread library. My problem is with sleep function.
am waking a thread which was slept using SIGALRM signal generated by ualarm function.
when multiple threads were set to sleep with different sleep times how can I identify when the timer fires which thread must I remove from sleep queue....??
How to differentiate alarm signal of different threads??
The signal handler is called from the context of the target thread. Hence, thread-specific storage works as expected (I tested it on Linux and Solaris). From the signal handler use the unix self-pipe trick to communicate from the signal handler back to the thread:
__thread int signal_pipe; // The write end.
extern "C" void signal_handler(int signo, siginfo_t*, void*)
{
if(!signal_pipe) // programming error: signal is being delivered to a wrong thread.
abort();
unsigned char signo_byte = static_cast<unsigned>(signo);
// standard unix self pipe trick
write(signal_pipe, &signo_byte, 1);
}
Each thread using this signal handler must create its own pipe and initialize signal_pipe with the write end of that pipe.

How to check SDL condition variables is waiting or not?

I am writing a SDL multithread application. My application has some threads that waits for signal by using SDL_CondWait.
SDL_LockMutex(mutex);
SDL_CondWait(cond,mutex);
SDL_UnlockMutex(mutex);
When users exit, I want to wake up the threads to let the application exit. However, when I used SDL_CondSignal to signal the conditional variables, the application sometimes got errors.
SDL_CondSignal(cond);
I guessed that is because at that moment, the condition varialbe isn't waiting.
My question is how to check whether SDL condition variables is waiting ?
struct SDL_cond
{
SDL_mutex *lock;
int waiting;
int signals;
SDL_sem *wait_sem;
SDL_sem *wait_done;
};
The waiting struct field holds amount of threads that the are blocked.
Also, if you want to wake up all threads, you should call SDL_CondBroadcast. SDL_CondSignal wakes up only one of the threads.

Thread, ansi c signal and Qt

I'm writing a multithread plugin based application. I will not be the plugins author. So I would wish to avoid that the main application crashes cause of a segmentation fault in a plugin. Is it possible? Or the crash in the plugin definitely compromise also the main application status?
I wrote a sketch program using qt cause my "real" application is strongly based on qt library. Like you can see I forced the thread to crash calling the trimmed function on a not-allocated QString. The signal handler is correctly called but after the thread is forced to quit also the main application crashes. Did I do something wrong? or like I said before what I'm trying to do is not achievable?
Please note that in this simplified version of the program I avoided to use plugins but only thread. Introducing plugins will add a new critical level, I suppose. I want to go on step by step. And, overall, I want to understand if my target is feasible. Thanks a lot for any kind of help or suggestions everyone will try to give me.
#include <QString>
#include <QThread>
#include<csignal>
#include <QtGlobal>
#include <QtCore/QCoreApplication>
class MyThread : public QThread
{
public:
static void sigHand(int sig)
{
qDebug("Thread crashed");
QThread* th = QThread::currentThread();
th->exit(1);
}
MyThread(QObject * parent = 0)
:QThread(parent)
{
signal(SIGSEGV,sigHand);
}
~MyThread()
{
signal(SIGSEGV,SIG_DFL);
qDebug("Deleted thread, restored default signal handler");
}
void run()
{
QString* s;
s->trimmed();
qDebug("Should not reach this point");
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread th(&a);
th.run();
while (th.isRunning());
qDebug("Thread died but main application still on");
return a.exec();
}
I'm currently working on the same issue and found this question via google.
There are several reasons your source is not working:
There is no new thread. The thread is only created, if you call QThread::start. Instead you call MyThread::run, which executes the run method in the main thread.
You call QThread::exit to stop the thread, which is not supposed to directly stop a thread, but sends a (qt) signal to the thread event loop, requesting it to stop. Since there is neither a thread nor an event loop, the function has no effect. Even if you had called QThread::start, it would not work, since writing a run method does not create a qt event loop. To be able to use exit with any QThread, you would need to call QThread::exec first.
However, QThread::exit is the wrong method anyways. To prevent the SIGSEGV, the thread must be called immediately, not after receiving the (qt) signal in its event loop. So although generally frowned upon, in this case QThread::terminate has to be called
But it is generally said to be unsafe to call complex functions like QThread::currentThread, QThread::exit or QThread::terminate from signal handlers, so you should never call them there
Since the thread is still running after the signal handler (and I'm not sure even QThread::terminate would kill it fast enough), the signal handler exits to where it was called from, so it reexecutes the instruction causing the SIGSEGV, and the next SIGSEGV occurs.
Therefore I have used a different approach, the signal handler changes the register containing the instruction address to another function, which will then be run, after the signal handler exits, instead the crashing instruction. Like:
void signalHandler(int type, siginfo_t * si, void* ccontext){
(static_cast<ucontext_t*>(ccontext))->Eip = &recoverFromCrash;
}
struct sigaction sa;
memset(&sa, 0, sizeof(sa)); sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = &signalHandler;
sigaction(SIGSEGV, &sa, 0);
The recoverFromCrash function is then normally called in the thread causing the SIGSEGV. Since the signal handler is called for all SIGSEGV, from all threads, the function has to check which thread it is running in.
However, I did not consider it safe to simply kill the thread, since there might be other stuff, depending on a running thread. So instead of killing it, I let it run in an endless loop (calling sleep to avoid wasting CPU time). Then, when the program is closed, it sets a global variabel, and the thread is terminated. (notice that the recover function must never return, since otherwise the execution will return to the function which caused the SIGSEGV)
Called from the mainthread on the other hand, it starts a new event loop, to let the program running.
if (QThread::currentThread() != QCoreApplication::instance()->thread()) {
//sub thread
QThread* t = QThread::currentThread();
while (programIsRunning) ThreadBreaker::sleep(1);
ThreadBreaker::forceTerminate();
} else {
//main thread
while (programIsRunning) {
QApplication::processEvents(QEventLoop::AllEvents);
ThreadBreaker::msleep(1);
}
exit(0);
}
ThreadBreaker is a trivial wrapper class around QThread, since msleep, sleep and setTerminationEnabled (which has to be called before terminate) of QThread are protected and could not be called from the recover function.
But this is only the basic picture. There are a lot of other things to worry about: Catching SIGFPE, Catching stack overflows (check the address of the SIGSEGV, run the signal handler in an alternate stack), have a bunch of defines for platform independence (64 bit, arm, mac), show debug messages (try to get a stack trace, wonder why calling gdb for it crashes the X server, wonder why calling glibc backtrace for it crashes the program)...

How can a process kill itself?

#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
int main(){
pid_t pid = fork();
if(pid==0){
system("watch ls");
}
else{
sleep(5);
killpg(getpid(),SIGTERM); //to kill the complete process tree.
}
return 0;
}
Terminal:
anirudh#anirudh-Aspire-5920:~/Desktop/testing$ gcc test.c
anirudh#anirudh-Aspire-5920:~/Desktop/testing$ ./a.out
Terminated
for the first 5 secs the output of the "watch ls" is shown and then it terminates because I send a SIGTERM.
Question: How can a process kills itself ? I have done kill(getpid(),SIGTERM);
My hypothesis:
so during the kill() call the process switches to kernel mode. The kill call sends the SIGTERM to the process and copies it in the process's process table. when the process comes back to user mode it sees the signal in its table and it terminates itself (HOW ? I REALLY DO NOT KNOW )
(I think I am going wrong (may be a blunder) somewhere in my hypothesis ... so Please enlighten me)
This code is actually a stub which I am using to test my other modules of the Project.
Its doing the job for me and I am happy with it but there lies a question in my mind how actually a process kills itself. I want to know the step by step hypothesis.
Thanks in advance
Anirudh Tomer
Your process dies because you are using killpg(), that sends a signal to a process group, not to a process.
When you fork(), the children inherits from the father, among the other things, the process group. From man fork:
* The child's parent process ID is the same as the parent's process ID.
So you kill the parent along with the child.
If you do a simple kill(getpid(), SIGTERM) then the father will kill the child (that is watching ls) and then will peacefully exit.
so during the kill() call the process switches to kernel mode. The kill call sends the SIGTERM to the process and copies it in the process's process table. when the process comes back to user mode it sees the signal in its table and it terminates itself (HOW ? I REALLY DO NOT KNOW )
In Linux, when returning from the kernel mode to the user-space mode the kernel checks if there are any pending signals that can be delivered. If there are some it delivers the signals just before returning to the user-space mode. It can also deliver signals at other times, for example, if a process was blocked on select() and then killed, or when a thread accesses an unmapped memory location.
I think it when it sees the SIGTERM signal in its process tables it first kills its child processes( complete tree since I have called killpg() ) and then it calls exit().
I am still looking for a better answer to this question.
kill(getpid(), SIGKILL); // itself I think
I tested it after a fork with case 0: and it quit regular from separate parent process.
I don't know if this is a standard certification method ....
(I can see from my psensor tool that CPU usage return in 34% like a normal program code with
a counter stopped ) .
This is super-easy in Perl:
{
local $SIG{TERM} = "IGNORE";
kill TERM => -$$;
}
Conversion into C is left as an exercise for the reader.

Resources