non-reentrant function in signal handler? - handler

consider a signal handler that call exit() as last instruction:
is safe to call non-reentrant functions (e.g. free()) in that handler?
IMHO it would be legal due to the fact that the handler does not return
to the normal sequence of execution.
Thank you in advance.

No, this is illegal, more then that, there are very few safe functions to call.
There is a list of safe functions to call, see http://linux.die.net/man/2/signal Notes section.

You must distinguish between two signals: Those which tell the daemon to "reload" and those which terminate the daemon ("kill"). In the "kill" case, you don't need to free anything. Your process is going to die, the OS will clean up anything you have allocated. If you use shared memory, you must do the cleanup when you're started again. Don't do anything in the "kill" handler which might cause problems. Just die.
In the reload case, you can call any function you like since the user wants you to "shut down orderly". In this case, there is little chance that you will get the same signal again (so it doesn't matter whether a function is reentrant or not).

Reentrancy as more to do with the "entrance" to a function and, side-effects and state maintained by the said function than the exit...
You might want to consult this man page.

Related

VB.Net: appropriate synchronisation object for waiting, not protecting

I have BBController instances (my custom objects), where some may need to wait for a few others to complete first (dependencies). I have decided to have each controller lock some synchronisation object at initialisation, lets call it a Padlock, and then unlock it when its done processing. When its unlocked, any controllers that depend (or were waiting for) on the aforementioned controller can then continue. So this is not about protecting a section of code by allowing one thread, but instead telling anything that that depends on an output to wait until that output is available.
I have experience with Semaphores in objective c, so I thought I could use those here by having each controller initialise its semaphore with a value of 0, and then when finished signal it with a value of infinite or max. While that would work, I'm sure there is a better locking object to make use of, since the value property of Semaphore is of no use here since as many BBControllers can continue when the semaphore is signalled. I am new to VB.Net

Cocoa Setting Terminal Exit Code Variable

I would like to be able to set a terminal variable; basically what I want to do is assign my own exit code through my app. My research finds that NSTask maybe the way to do this, but I can't say for sure how to go on about this since I know for one, I do not know if I can have a setLaunchPath:.
Here is an example of what I would type in the terminal:
bash-3.2$ $(exit 15); echo ${?};
15
Sorry if the question doesn't sound very technical. Please ask if you need clarifications. Thx in advance.
This isn't a good fit with a Cocoa application. Or are you considering a Foundation command-line tool?
First, it's not typical to invoke a Cocoa application from a command-line shell. If you do, it's most common to do so using the /usr/bin/open command, which is not normally synchronous and so doesn't convey the app's exit status to the shell.
Second, the process which exits does not directly set the shell variable. It exits with a status code and that's stored in the kernel. The shell then obtains that status code from the kernel and sets its own variable. It is not generally possible for one process to set an environment variable (or any other state) in another process (other than one it spawns itself) without that other process's cooperation.
Third, a Cocoa application typically quits using -[NSApplication terminate:]. That doesn't provide a way to tell the framework what value to use as the exit status code. NSApplicationMain(), which is what's typically called by the app's main() function, is documented to never return and to call exit(). The documentation suggests that it may specify some meaningful status code – "If you want to determine why the application exited, you should look at the result code from the exit function instead." – but not what that might be nor any way to influence it.
You might call exit() yourself from the -applicationWillTerminate: method of your application delegate. That way, you get to specify the status code. I'm not sure, though, if that might break any final cleanup that Cocoa might do. For example, if you have promised some data to the pasteboard, Cocoa requests that you provide it before your application terminates. I'm not sure if that occurs before or after -applicationWillTerminate: (probably before). That delegate call is in response to the application object posting the NSApplicationWillTerminateNotification notification and there may be other observers of that notification. The order in which observers get notified is not specified, so the app delegate is not necessarily the last thing that would get it.

What high level synchronisation construct should be used for thread safe single shot method?

I have a situation where a session of background processing can finish by timing out, user asynchronously cancelling or the session completing. Any of those completion events can run a single shot completion method. The completion method must only be run once. Assume that the session is an instance of an object so any synchronisation must use instance constructs.
Currently I'm using an Atomic Compare and Swap operation on a completion state variable so that each event can test and set the completion state when it runs. The first completion event to fire gets to set the completed state and run the single shot method and the remaining events fail. This works nicely.
However I can't help feeling that I should be able to do this in a higher level way. I tried using a Lock object (NSLock as I'm writing this with Cocoa) but then got a warning that I was releasing a lock that was still in the locked state. This is what I want of course. The lock gets locked once and never unlocked but I was afraid that system resources representing the lock might get leaked.
Anyway, I'm just interested as to whether anyone knows of a more high level way to achieve a single shot method like this.
sample code for any of the completion events:
if(OSAtomicCompareAndSwapInt(0, 1, &completed))
{
self.completionCallback();
}
Doing a CAS is almost certainly the right thing to do. Locks are not designed for what you need, they are likely to be much more expensive and are semantically a poor match anyway -- the completion is not "locked". It is "done". A boolean flag is the right representation, and doing a CAS ensures that it is manipulated safely in concurrent scenarios. In C++, I'd use std::atomic_flag for this, maybe check whether Cocoa has anything similar (this just wraps the CAS in a nicer interface, so that you never accidentally use a non-CAS test on the variable, which would be racy).
(edit: in pthreads, there's a function called pthread_once which does what you want, but I wouldn't know about Cocoa; the pthread_once interface is quite unwieldy anyway, in my opinion...)

Should my block based methods return on the main thread or not when creating an iOS cloud integration framework?

I am in the middle of creating a cloud integration framework for iOS. We allow you to save, query, count and remove with synchronous and asynchronous with selector/callback and block implementations. What is the correct practice? Running the completion blocks on the main thread or a background thread?
For simple cases, I just parameterize it and do all the work i can on secondary threads:
By default, callbacks will be made on any thread (where it is most efficient and direct - typically once the operation has completed). This is the default because messaging via main can be quite costly.
The client may optionally specify that the message must be made on the main thread. This way, it requires one line or argument. If safety is more important than efficiency, then you may want to invert the default value.
You could also attempt to batch and coalesce some messages, or simply use a timer on the main run loop to vend.
Consider both joined and detached models for some of your work.
If you can reduce the task to a result (remove the capability for incremental updates, if not needed), then you can simply run the task, do the work, and provide the result (or error) when complete.
Apple's NSURLConnection class calls back to its delegate methods on the thread from which it was initiated, while doing its work on a background thread. That seems like a sensible procedure. It's likely that a user of your framework will not enjoy having to worry about thread safety when writing a simple callback block, as they would if you created a new thread to run it on.
The two sides of the coin: If the callback touches the GUI, it has to be run on the main thread. On the other hand, if it doesn't, and is going to do a lot of work, running it on the main thread will block the GUI, causing frustration for the end user.
It's probably best to put the callback on a known, documented thread, and let the app programmer make the determination of the effect on the GUI.

Objective C: How to kill a thread while in another thread in Objective-C?

I was trying to set up a multi thread app. One of the threads is working as background to get some data transfer. Right now this thread automatically kill itself after it's job done.
Somehow I need to kill this thread in another thread in order stop its job immediately. Are there any api or method for making this happen?
In short, you can't. Or, more precisely, you should not. Not ever and not under any circumstances.
There is absolutely no way for thread A to know the exact state of thread B when A kills B. If B is holding any locks or in the middle of a system call or calling into a system framework when A kills it, then the resulting state of your application is going to be nondeterministic.
Actually -- it will be somewhat deterministic in that you are pretty much guaranteed that a crash will happen sometime in the near future.
If you need to terminate thread B, you need to do so in a controlled fashion. The most common way is to have a cancel flag or method that can be set/called. thread B then needs to periodically check this flag or check to see if the method has been called, clean up whatever it is doing, and then exit.
That is, you are going to have to modify the logic in thread B to support this.
bbum is correct, you don't want to simply kill a thread. You can more safely kill a process, because it is isolated from the rest of the system. Because a thread shares memory and resources with the rest of the process, killing it would likely lead to all sorts of problems.
So, what are you supposed to do?
The only correct way of handling this is to have a way for your main thread to send a message to the worker thread telling it to quit. The worker thread must check for this message periodically and voluntarily quit.
An easy way to do this is with a flag, a boolean variable accessible by both threads. If you have multiple worker threads, you might need something more sophisticated, though.
Isn't that a bad idea? (If the other thread is in the middle of doing something in a critical section, it could leave stuff in an inconsistent state.) Couldn't you just set some shared flag variable, and have the other thread check it periodically to see if it should stop?
One thing you could do would be pass messages between the front thread and the background thread, potentially using something like this to facilitate message passing.
If you are using pthread then you try with 'pthread_kill' , I had tried long back it did not worked for me, basically if the thread is in some blocking call it won't work.
It is true that killing a thread is not good option, if you are looking for some kind for fix for some issue then you can try with this.
In my personal view it is best to let a thread run its course naturally. It's difficult to make guarantees about the effect of trying to kill a thread.