Dbus - fault control - dbus

Is there a method to inform a process connected via Dbus that the other process died?I mean could the faulty process inform the other one that he had an abnormal termination. I know that you can check the error type return but i want something else. For exemple consider we have a process waiting for an answer but we kill the other process with CTRL+C. Is there a way of notifing the other process..or you should just wait a few seconds for the response...etc

At a low level: you can connect to the NameOwnerChanged signal on the D-Bus daemon, which is emitted whenever a name is claimed or released on the bus. So if the worker process takes the well-known name com.example.Foo, you can add a match rule for sender=org.freedesktop.DBus,path=/org/freedesktop/DBus,interface=org.freedesktop.DBus,member=NameOwnerChanged,type=signal,arg0=com.example.Foo. (The arg0 part of the match rule prevents you being notified for services other than the one you care about.)
Higher level: if you're waiting on the result of a method call, your binding (such as QDBus or GDBus) should call your callback with an error telling you that this is what happened. But you can also use a higher-level API for watching NameOwnerChanged. For GDBus, see the g_bus_watch family of functions.

Related

Check if pthread is still alive in Linux C

I know similar questions have been asked, but I think my situation is little bit different. I need to check if child thread is alive, and if it's not print error message. Child thread is supposed to run all the time. So basically I just need non-block pthread_join and in my case there are no race conditions. Child thread can be killed so I can't set some kind of shared variable from child thread when it completes because it will not be set in this case.
Killing of child thread can be done like this:
kill -9 child_pid
EDIT: alright, this example is wrong but still I'm sure there exists way to kill a specific thread in some way.
EDIT: my motivation for this is to implement another layer of security in my application which requires this check. Even though this check can be bypassed but that is another story.
EDIT: lets say my application is intended as a demo for reverse engineering students. And their task is to hack my application. But I placed some anti-hacking/anti-debugging obstacles in child thread. And I wanted to be sure that this child thread is kept alive. As mentioned in some comments - it's probably not that easy to kill child without messing parent so maybe this check is not necessary. Security checks are present in main thread also but this time I needed to add them in another thread to make main thread responsive.
killed by what and why that thing can't indicate the thread is dead? but even then this sounds fishy
it's almost universally a design error if you need to check if a thread/process is alive - the logic in the code should implicitly handle this.
In your edit it seems you want to do something about a possibility of a thread getting killed by something completely external.
Well, good news. There is no way to do that without bringing the whole process down. All ways of non-voluntary death of a thread kill all threads in the process, apart from cancellation but that can only be triggered by something else in the same process.
The kill(1) command does not send signals to some thread, but to a entire process. Read carefully signal(7) and pthreads(7).
Signals and threads don't mix well together. As a rule of thumb, you don't want to use both.
BTW, using kill -KILL or kill -9 is a mistake. The receiving process don't have the opportunity to handle the SIGKILL signal. You should use SIGTERM ...
If you want to handle SIGTERM in a multi-threaded application, read signal-safety(7) and consider setting some pipe(7) to self (and use poll(2) in some event loop) which the signal handler would write(2). That well-known trick is well explained in Qt documentation. You could also consider the signalfd(2) Linux specific syscall.
If you think of using pthread_kill(3), you probably should not in your case (however, using it with a 0 signal is a valid but crude way to check that the thread exists). Read some Pthread tutorial. Don't forget to pthread_join(3) or pthread_detach(3).
Child thread is supposed to run all the time.
This is the wrong approach. You should know when and how a child thread terminates because you are coding the function passed to pthread_create(3) and you should handle all error cases there and add relevant cleanup code (and perhaps synchronization). So the child thread should run as long as you want it to run and should do appropriate cleanup actions when ending.
Consider also some other inter-process communication mechanism (like socket(7), fifo(7) ...); they are generally more suitable than signals, notably for multi-threaded applications. For example you might design your application as some specialized web or HTTP server (using libonion or some other HTTP server library). You'll then use your web browser, or some HTTP client command (like curl) or HTTP client library like libcurl to drive your multi-threaded application. Or add some RPC ability into your application, perhaps using JSONRPC.
(your putative usage of signals smells very bad and is likely to be some XY problem; consider strongly using something better)
my motivation for this is to implement another layer of security in my application
I don't understand that at all. How can signal and threads add security? I'm guessing you are decreasing the security of your software.
I wanted to be sure that this child thread is kept alive.
You can't be sure, other than by coding well and avoiding bugs (but be aware of Rice's theorem and the Halting Problem: there cannot be any reliable and sound static source code program analysis to check that). If something else (e.g. some other thread, or even bad code in your own one) is e.g. arbitrarily modifying the call stack of your thread, you've got undefined behavior and you can just be very scared.
In practice tools like the gdb debugger, address and thread sanitizers, other compiler instrumentation options, valgrind, can help to find most such bugs, but there is No Silver Bullet.
Maybe you want to take advantage of process isolation, but then you should give up your multi-threading approach, and consider some multi-processing approach. By definition, threads share a lot of resources (notably their virtual address space) with other threads of the same process. So the security checks mentioned in your question don't make much sense. I guess that they are adding more code, but just decrease security (since you'll have more bugs).
Reading a textbook like Operating Systems: Three Easy Pieces should be worthwhile.
You can use pthread_kill() to check if a thread exists.
SYNOPSIS
#include <signal.h>
int pthread_kill(pthread_t thread, int sig);
DESCRIPTION
The pthread_kill() function shall request that a signal be delivered
to the specified thread.
As in kill(), if sig is zero, error checking shall be performed
but no signal shall actually be sent.
Something like
int rc = pthread_kill( thread_id, 0 );
if ( rc != 0 )
{
// thread no longer exists...
}
It's not very useful, though, as stated by others elsewhere, and it's really weak as any type of security measure. Anything with permissions to kill a thread will be able to stop it from running without killing it, or make it run arbitrary code so that it doesn't do what you want.

What does it mean to send a message to a thread?

I am learning about threads. And I need to understand how threads communicate between each other, so what does it mean when we say something like "let Thread A send a message to Thread B"?
I can think of the following:
Thread B is blocking on some sort of queue, and Thread A places a new
entry in this queue, which causes Thread B to unblock, and retrieve
this entry.
Thread B is blocking on an event (for example, in Windows API there
is the Event object), and Thread A signals this event which will
cause Thread B to wake up (or is this called notifying a thread and
not sending a message to it?)
The "threads" world is subject of many ambiguity due to different nomenclature coming from different environments, sometimes using same words to mean different things.
Your first assertion makes sense in very general terms: the "message" is what makes the thread to wake-up and get some "input".
Depending on the OS and its own API, your second assertion makes sense and is nothing more then a way to implement the first using the Win32 API.
Another possible interpretation can be that the thread is blocked on a message loop (see GetMessage) and the other one calls PostThreadMessage.
In a more general term, you can think of a "message" as an "event" that carries a "state" with it: an event simply happens (and that's all the information it gives). A message "happens", and has some parameter associated with it.
Link to example Windows code that uses two threads to copy a file, the original thread reads, a created thread writes. There's a custom messaging system that uses Windows mutexes and semaphores. Other than the overhead to create and delete the mutexes and semaphores, the actual functions are fairly small. I've worked on embedded multi-threaded devices, using a similar messaging interface scheme.
http://rcgldr.net/misc/mtcopy.zip

Quit multithreaded/multi-process web server

I am programming a http server. There is the main daemon spawning a bunch of listeners, which are threads or processes, depending on user settings. Upon creation of a listener, the socket descriptor is passed to it, and its job is just to listen for connections (duh). A semaphore is wrapping the call to listen as to avoid the thundering herd effect.
My problem is how to quit the server. In this situation, where the listeners are blocked on a semaphore, how does the daemon is going to tell them to close? The daemon can't just kill them, maybe someone is responding to a request...
I want to keep the design as simple as possible, but I can't find a solution to this problem.
Here are some ugly workaround:
Set a timeout for the semaphore. Wake up. Should I close? No? Ok, back to sleep;
Just kill them;
Array of booleans in shared memory, meaning responding/blocked, the daemon kills accordingly. The best so far, but not so simple.
What do you say?
Thanks.
A clean way to solve this problem is to make each listener wait on two semaphores. The first one it the current one you now use, and a second one, that when become signaled, means it's time to quit. I believe your system is linux since you used the term daemon. The function select does just that - waits on multiple objects (file-descriptors like), and returns when one of them becomes signaled. You also know from the function which one got signaled, so here is your solution.
On Windows the function is WaitForMultipleObjects()
Send a SIGTERM or, if you prefer, SIGUSR to children and implement handling of this signal so that they finish current request and exit gracefully.
If they wait on semaphore, you should use interruptible mode so that receiving a signal will wake them up.
In the past I've used a global that client handling threads could use to find out if they need to 'clean up shop' and then waited on them to all finish but I'd also be interested to know if there's an even better way. (Not sure what language but in most, you can check to see if your thread is still running.)

Is there a way to identify how may signals delivered, pending to given process id?

Given a process id, I would like to find how may signals { including real time signals } are delivered, and handled. Is there any way to get from /proc file system?, If so, how to do that ?. Kindly guide.
Referring "pending signals":
One can use sigpending() to get a set of types of signals pending for a given process. This isn't the actual number of signals that had been sent to the process.
Referring "delivered signals":
One can set up a signal handler using sigaction() which in turn can count how often it is called. Anyhow the kernel or the run-time library (I'm not sure which) might decided to only call the handlers once for one or more signals of the same type having been sent close together in time.
An alternative way to collect signals is the use of sigwaitinfo(), probably in a dedicated thread.

determine if a process is dead or not - by PID

I have two different way to check whether a process is still up and running:
1) using GetExitCodeProcess()
2) walking the list of processes using CreateToolhelp32Snapshot() and checking PIDs
now, in both cases I'm still getting that a process that I terminated with TerminateProcess is till alive even tho it is not.
Is there a way to positively know whether a process is still alive or dead passing the PID?
thanks!
Don't use PID for something like this. PIDs are reused and have a very narrow range, with a very high collision probability. In other words, you will find a running process but will be a different process.
A call to GetExitCodeProcess should return STILL_ACTIVE for active processes. After a call to TerminateProcess, the process will be dead, and a different value will be returned.
Another way to check if a process is alive is WaitForSingleObject. If you call this on the process handle with a timeout of 0, it will immediately return WAIT_TIMEOUT if the process is still running.
You cannot assume a low level API call functions the way it seems or how you think it should function from its name or high level description. A kernel still has things to do and often calls are just requests to the kernel and there are a multitude of things a kernel needs to do (depending on implementation) before it will actually release the PID. In this case after you issue the call you may assume the process is dead, however the kernel still has to clean up.
From MSDN :
The TerminateProcess function is use
to unconditionally cause a process to
exit. The state of global data
maintained by dynamic-link libraries
(DLLs) may be compromised if
TerminateProcess is used rather than
ExitProcess.
TerminateProcess initiates termination
and returns immediately. This stops
execution of all threads within the
process and requests cancellation of
all pending I/O. The terminated
process cannot exit until all pending
I/O has been completed or canceled.
A process cannot prevent itself from
being terminated.
Could you make use of the Process Status API? There are functions for enumerating all running processes on a system - this could help you.

Resources