Catch App Terminate from LaunchDeamon - cocoa

I've got a Cocoa foundation tool that I run as a LaunchDeamon. When the app is terminated by the system, either by a reboot or shutdown (or even launchctl unload), is there a way I can capture this event so that I can perform some finalizing functions?

All the cases you're discussing send SIGTERM to the process. You want to add a signal handler for that. See the man pages for signal and sigaction. Read the warnings carefully. Only certain functions are legal to call during a signal handler (and in principle you should never allocate heap memory). Generally it's best to just use the handler to set a flag that tells your main thread to terminate.
You may also want to look at PreLoginAgents for an example of how to handle SIGTERM using the run loop, if you're using a run loop.
See Terminating Processes in the Daemons and Services Programming Guide for full details on what signals will be sent to your process.

All NSObject subclasses call a method before dying: - finalize. There is also NSSetUncaughtExceptionHandler for dealing with crashes.

Related

Is it possible to sending a signal to a process in Darwin/XNU/OSX/macOS?

I've been working on a system program targeted for POSIX but I've run into the problem of not having access to sigqueue. Does Darwin/XNU have an alternative way of sending signals to another process? I've seen kill() but nothing else.
After reading the POSIX standard, I came to understand that kill had been extended to so that you can actually send any kind of signal that you specify and will not automatically cause the receiving application to terminate (unless you send SIGKILL).

ExitProcess behaviour in Windows in relation to atexit handlers

I want to be able to catch any attempts of executing exit()/ExitProcess()/TerminateProcess() or any other such calls.
I thought about registering a handler with atexit(). This works fine for normal program termination (return from main()) or exit() calls (regardless of the thread that calls exit()), but ExitProcess() and TerminateProcess() bypass the handler I registered.
ExitProcess() documentation states:
Note that returning from the main function of an application results
in a call to ExitProcess.
But the observed behaviour is at least different in this regard.
Is there a method of registering a handler for process exit/termination what will always be called (except for external calls to TerminateProcess(), unhandled exceptions thrown by one of my threads or __failfast() calls, I'm guessing these are really impossible to catch).
There is the dirty option of hooking ExitProcess(), but I'd rather not do that.
EDIT: just so this is clear: I'm interested in my own process, not monitoring / controlling another process.
There is a Kernel Mode Event a device driver can subscribe to in order to get notifications of terminations of processes. This is preferred over trying to inject a DLL into processes for API hooks due to the myriad number of internal and external ways that process may end.

Detach debugger(unknown) from process?

I am trying to attach debugger(windbg,ollydbg) to running process but there's an error saying Debugger is already attached then how can i detach that unknown debugger from that process?
Process includes multi thread, one thread can be attached to debugger and other can't.
The process might be spawning a second process which attaches to the first process for debugging using DebugActiveProcess() in order to prevent people from debugging the first process. Keep in mind that a process cannot debug itself using this method, so a second process must be spawned to do this.
Things you could try:
Use any sort of process monitor or even task manager to figure out what process the first process spawns
Inject code into the second process to call DebugActiveProcessStop() to detach it from the first process
Hook DebugActiveProcess() (kernel32.DebugActiveProcess, ntdll.ZwDebugActiveProcess, or in kernelmode) and redirect it to attach to a different dummy process
Kill the second process
Prevent the second process from getting a handle to the first process with the needed permissions - DebugActiveProcess() will then fail
Use alternative debugging methods (Cheat engine with VEH debugging for example) that don't use the normal debugging API's and therefore bypass this problem

In Windows 7, how to send a Ctrl-C or Ctrl-Break to a separate process

Our group has long running processes which run daily. The processes are typically started at 9pm on any given day and run until 7pm the next day. Thus they typically run 22hrs/day. They are started by scheduled tasks on servers under a particular generic user ID, and they start and run regardless of whether or not that user ID is logged on. Thus, they are windowless console executables.
The tasks orchestrate computations running on a large server farm. Generally these controlling tasks run uninterrupted for the full 22hrs/day. However, we often have a need to stop and restart these processes. Because they control a multitude of tasks running on our server farm, it is important that they be shut down cleanly, so that they can stop and shut down all the server farm processes. Which brings me to our problem.
The controlling process has been programmed to respond to ctrl-C and ctrl-break signals. This works fine when the process is manually started in a console where we have access to the console and can "type" ctrl-c or ctrl-break in the console window. However, as mentioned, the processes typically run as windowless scheduled tasks. Hence we cannot "type" anything into a non-existent console window. Because they are console processes that execute without a logon process, the also must be able to execute in a completely windowless environment. So, how do we set up the process to listen for a shut-down signal?
While the process does indeed listen for a ctrl-C and ctrl-break signal, I can see no way to send that signal to a process. This seems to be a fundamental problem in Windows, or am I wrong? I am aware of SendSignal.exe, but so far have been unable to get it to work. It fails as follows:
>SendSignal 26320
Sending signal to process 26320...
CreateRemoteThread failed with 0x00000005.
StartRemoteThread failed with 0x00000005.
0x00000005 == Access is denied.
Trying "taskkill" without -F results in:
>taskkill /PID 24840
ERROR: The process with PID 24840 could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
All other "kill" functions kill the process immediately rather than sending a signal.
One possible solution would be a file-watch based solution: create a watch for some modification of a specific file. But this is a hack and we would prefer to do it with appropriate signaling. Has anyone solved this issue? It seems to be so very basic a functionality, and it is certainly trivial to do it in a Unix environment. Surely Microsoft has provided SOME mechanism to allow clean shut down of a windowless executable?
I am aware of the thread below, whose question is virtually identical (save for the specification of why the answer is necessary, i.e. why one needs to be able to do this for a windowless, console-less process), but there is no answer there excpet for "use SendSignal", which, as I said, does not work for us:
Can I send a ctrl-C (SIGINT) to an application on Windows?
There are other similar questions, but no answers as yet.
Any help appreciated.
[Upgrading #Anon's comment to an answer for visibility]
windows-kill worked perfectly and managed to resolve access denial issues faced with SendSignal. A privileged user would have to run it as well of course.
windows-kill also supports both ctrl-c and ctrl-break signals.

Start and monitor multiple instances of one process in Windows

I have a Windows application of which I need multiple instances running, with different command line parameters. The application is quite unstable and tends to crash every 48 hours or so.
Since manual checking for failure and restarting in case of one isn't what I love to do I want to write a "manager program" for this. It would launch the program (all its instances) and then watch them. In case a process crashes it would be restarted.
In Linux I could achieve this with fork()s and pids, but this obviously is not available in Windows. So, should I try to implement a CreateProcess version or is there a better way?
When you call CreateProcess, you are returned a handle to the new process in the hProcess member of the process information struct that you pass to CreateProcess. You can use this handle to detect when the process terminates.
For instance, you can create another thread and call WaitForSingleObject(hProcess) and block until the process terminates. Then you can decide whether or not to restart it.
Or your could call GetExitCodeProcess(hProcess, &exitcode) and test exitcode. If it has the value STILL_ACTIVE then your process has not terminated. This approach based on GetExitCodeProcess necessitates polling.
If it can be run as a daemon, the simplest way to ensure it keep running is Non-Sucking Service Manager.
It will allow to run as win32 service applications not designed as services. It will monitor and restart if necessary. And the source code is included, if any customization is needed.
All you need to do is define each of your instances as a service, with the required parameters, at it will do the rest.
If you have some kind of security police limitation and can't use third party tools, then coding will be necessary. The answer from David Heffernan gives you the appropiate direction.
Or it can be done in batch, vbs or js without need of anything out of the system. WMI Win32_Process class should allow you to handle it.

Resources