How to cancel a process waiting to return with ptrace() - system-calls

I am trying to cancel when a process calls wait(), read(), recvfrom() or similar, because if I use ptrace on it, after the PTRACE_ATTACH and later PTRACE_CONT, my tracer becomes blocked until the function in the tracee returns. Also I think it happens the same with sleep().
Would be possible to cancel the call, or reproduce a fake return?
Thanks.

Yes, you should send a PTRACE_INTERRUPT. This will trigger the syscall to exit.
To do this, you need not to waitpid on your tracee, because that would block you (the tracer) too.
You can either have multiple threads: one that will block on the tracee, one that will "decide" to cancel the blocking syscall - e.g. a GUI thread that the user will press "cancel" (like a normal debugger, e.g. GDB).
Or you can use PTRACE_SYSCALL to manually diagnose every syscall the program is doing and then decide preemptively if you wish to execute that syscall. This way you can decide to not run wait at all, or perhaps mock them by having your return value instead.

Related

How to ensure the order of user callback function in OpenCL?

I am working on OpenCL implementation wherein the host side particular function has to call every time the clEnqueueReadBuffer is done executing.
I am calling the kernels in a loop. It will look like below in an ordered queue.
clEnqueueNDRangeKernel() -> clEnqueueReadBuffer(&Event) ->
clEnqueueNDRangeKernel() -> clEnqueueReadBuffer(&Event) .......
I have used clSetEventCall() to register Events in each read command to execute a callback function. I have observed that, though the command queue is an in-order queue, the order of the callback function does not execute in-order.
Also, in OpenCL 1.2, it has a mention as below.
The order in which the registered user callback functions are called
is undefined. There is no guarantee that the callback functions
registered for various execution status values for an event will be
called in the exact order that the execution status of a command
changes.
Can anyone give me a solution? I want to execute the callback function in order.
A simple solution could be to subscribe the same callback function to both events. In the callback code, you can check the status of each relevant event and perform the operation you want accordingly.
Note that on some implementations, the driver will batch multiple commands for execution.
The immediate effect is that that multiple events will be signaled "at once" even though the associated commands complete at a different time.
// event1 & event2 are likely to be signaled at once:
clEnqueueNDRangeKernel();
clEnqueueReadBuffer(&event1);
clEnqueueNDRangeKernel();
clEnqueueReadBuffer(&event2);
Wheres:
// event1 is likely to be signaled before event2:
clEnqueueNDRangeKernel();
clEnqueueReadBuffer(&event1);
clflush(queue);
clEnqueueNDRangeKernel();
clEnqueueReadBuffer(&event2);
clflush(queue);
I would also check on which exact thread the callbacks are invoked.
Is it the same thread each time? or a different one? If the implementation opens a new thread for this task, it might be wiser to open a single thread yourself and wait for events in the order that you wish.

How does the interrupt handler know to which thread pass the data?

Lets say that we are working in a unix shell and typed a command "ls". When we hit enter, an interrupt request (IRQ) is sent from a keyboard controller to a processor. When IRQ is received, the processor stops whatever it is doing, saves the execution context and runs the interrupt handler.
I am curious how does the information about what key has been pressed is passed to the interested thread (in our case it is a thread belonging to the unix shell process)? I guess that this is the role of the interrupt handler? The code that is running when the interrupt occurs doesn't have to be the code of the unix shell, right? Cause when the thread is waiting for the IO it is blocked?
The interrupt handler most likely just saves the key code in a data structure and signals some kind of event so the desktop/window_manager/whatever_it_is can then grab the data and make it available to the currently active (console) window.
Obviously, the data can arrive at any moment and not necessarily when your program (or shell) is waiting for it inside getchar() or similar. And the data needs to be buffered because of that asynchronous nature of its delivery.
The ISR has very little business knowing anything about the shell or your program or how that desktop thingy deals with the rest of the keyboard data delivery.

Does Perl safely defer INT signals during a Storable write?

I'm concerned about data corruption while executing a Storable::store operation. I'm writing about 100 MB to an NFS to backup my calculations at particular checkpoints but the process isn't exactly speedy.
To try to prevent corruption, I have a SIG{INT} signal handler. Right before Storable::store is called, a global variable is set indicating it isn't safe to terminate. As soon as Storable::store completes, that global variable is returned to a value to indicate it's okay to interrupt.
That global variable is used to indicate whether or not the signal handler will call die or whether it will just print a statement saying "Can't stop yet."
But am I really helping thing? I see now from reading perlipc that interrupting IO is sometimes done safely, and sometimes it is not... That is, should my signal handler end up being called in the middle of my Storeable::store operation, such a brief diversion to my signal handler subroutine may still be enough to screw things up.
Does anyone know how Storable performs in such a situation? Or is my signal handling setup actually appropriate?
Since 5.8.1, Perl uses "safe signals" (by default). When you setup a signal handler through %SIG, Perl actually installs a simple signal handler that does nothing but increment a counter. In between Perl ops, Perl checks if the counter is non-zero, and calls your signal handler if it is. That way, your signal handlers don't execute in the middle of a system call or library call.
There are only two things you need to worry about:
Modifying global vars (e.g. $!) in your signal handler.
System calls returning EINTR or EAGAIN because a signal came in during the call.
If you're really concerned that SIGINT could break store, try adding SA_RESTART to your signal handler. On Linux, this will force the system calls to be automatically retried upon a signal. This will probably defer your signal handler indefinitely since SIGINT will not be able to break out of the I/O operation. However, it should enable safe operation of Storable::store under any interruption circumstance.

In Scala, does Futures.awaitAll terminate the thread on timeout?

So I'm writing a mini timeout library in scala, it looks very similar to the code here: How do I get hold of exceptions thrown in a Scala Future?
The function I execute is either going to complete successfully, or block forever, so I need to make sure that on a timeout the executing thread is cancelled.
Thus my question is: On a timeout, does awaitAll terminate the underlying actor, or just let it keep running forever?
One alternative that I'm considering is to use the java Future library to do this as there is an explicit cancel() method one can call.
[Disclaimer - I'm new to Scala actors myself]
As I read it, scala.actors.Futures.awaitAll waits until the list of futures are all resolved OR until the timeout. It will not Future.cancel, Thread.interrupt, or otherwise attempt to terminate a Future; you get to come back later and wait some more.
The Future.cancel may be suitable, however be aware that your code may need to participate in effecting the cancel operation - it doesn't necessarily come for free. Future.cancel cancels a task that is scheduled, but not yet started. It interrupts a running thread [setting a flag that can be checked]... which may or may not acknowledge the interrupt. Review Thread.interrupt and Thread.isInterrupted(). Your long-running task would normally check to see if it's being interrupted (your code), and self-terminate. Various methods (i.e. Thread.sleep, Object.wait and others) respond to the interrupt by throwing InterruptedException. You need to review & understand that mechanism to ensure your code will meet your needs within those constraints. See this.

How to synchronise callback function when in a loop

I am pretty new to iPhone development. i need some help on how to synchronize a callback method and a for loop.
For example:
I have a for loop say 1 to 3.
Within this loop, first i send message to a receiver. The result from the receiver is obtained in a callback function. With this result i need to perform some parsing. Now how can i continue with the loop??
BR,
Suppi
Edited with Code:
-(void)requestData{
for (int i=1; i<3; i++) {
completeMessage = [self generateMessage:message];
[self sendMessageToReceiver:completeMessage];
//now it goes to the callback function to read message from receiver. How do i return to this point?? to continue the loop.
[self dosomething:result];
}
}
I don't know much about iPhone development but based on my asynchronous function calling experience you might have to reconsider your approach - assuming this is an asynchronous function call.
When you go through the loop the first time, your code is going to call all the asynchronous functions and move on. It is not going to wait. If you want it to wait for each function call then you either shouldn't use asynchronous functions or use a thread.wait or thread.sleep function in the loop. You could also use some kind of thread synchronization and signalling in the loop. For example, you could make the asynchronous call and then your thread waits until it gets a signal from your callback to continue.
You may want to take your custom end processing out of the loop and do it after all your callbacks are done. You could put state in a common location for each of your callbacks and use it after the callbacks are done.
Of course, you would need to wait until all the callbacks are done before you can continue.
Hope this helps.
Launch the message in a separate thread:
[receiver performSelectorInBackground:#selector(doSomething)];
use performSelectorInBackground:withObject: if you wish to pass a parameter.
Convert your "for" loop into the equivalent goto statements. Then break the goto basic blocks into methods and method calls without goto's. Then break the method containing the wait into 2 methods and use an asynchronous call and callback in between them. You may have to save some of the local and for loop's implicit state in instance variables.
Goto's are not always bad. They are just implicit in more readable structured and/or OOP messaging constructs. Sometimes the compiler can't do the conversion for you, so you need to know enough about raw program control sequencing to do it yourself.