How to Safely Force Shutdown of Mac - cocoa

What I want
I'm developing a little app to force me to only work at certain times of day - I need something to force me to stop working in the evenings so I can be more effective in the day.
The option within OS X to shut down my machine at a certain time is too easy to cancel. And you can always log back in afterwards.
I want my app to quit all applications whether they have unsaved work or not.
What I've tried
I thought of killing the loginwindow process, but I've read that this can cause data corruption.
I've come across the shutdown command - I'm using sudo shutdown -h +0 to shutdown immediately. This appears to be just the ticket, but I'm worried that it might cause data corruption if, say, Disk Utility is doing some kind of scan.
Is the shutdown command safe?
Can the shutdown command cause corruption? Or is it safe to use? Is there a better way of forcing shutdown safely?

Use AppleScript to tell application "System Events" to shut down.

The shutdown command sends running processes a signal to terminate, giving them a chance to do clean up work, if needed. So generally, when an application receives this signal (SIGTERM(inate)) it should wrap up and exit.
IIRC in Snow Leopard (10.6) Apple added something called fast-shutdown (or similar) which will send processes that have been flagged as being ok with it a SIGKILL signal, shutting them down without chance for cleanup work. This is supposed to make shutdown faster. The default is that applications still get SIGTERM and have to opt-in for SIGKILL; and they can mark themselves as "dirty", i. e. having unsaved work and do not want to be killed forcibly.
So while shutting down in the middle of a disk utility run will abort whatever disk utility is doing, IMHO it would not cause data corruption in general. However depending on the operation you are currently running, you could end up with an incomplete disk image or a half-formatted partition. Maybe you want to refrain from using it when you know the end of your configured work time is coming close.
Using cron to schedule the shutdown is a viable option if you want it to happen at a specified time. If you want it to happen after a certain amount of time after you log in, you could use the number parameter to shutdown to specify say 8 hours from now.

If you want to lose unsaved work then shutdown -h is your only answer.
However, anyone who has debugged a full-screen app on OS X knows that is it very easy (some say too easy) for an app to capture the screen and render the computer essentially useless (without SSHing from another computer to kill the process.) That's another alternative.

the recommended way to schedule a shutdown of your computer on a regular basis is in the system preferences -> Energy Saver panel. Click on the "schedule" button in the lower right hand corner. the rest is self explanatory...

Forcing your computer to shut down (and discard any unsaved work) doesn't sound like a good idea to me. Wouldn't it be easier and safer to just set an alarm clock to remind yourself when you should stop working, and walk away from your computer when it rings? (That's what I do.)
Edit: That might have come across as a bit rude, which was not my intention at all. (I had no intention of making fun of your question or anything like that.) I just think that this would be a better solution to this problem :)

Maybe cron is installed on your computer? It's wonderful =)

Related

What file access woke the sleeping disk in Windows?

Every now and then, my sleeping disk wakes up, does what sounds like a single read, and then sits idle until it falls asleep again. Sometimes a program that I am using completely freezes for about 10 seconds while the disk spins up, even though that program doesn't seem to need to read from that drive.
Is there an api for listening to file accesses as they happen, or similar, so I can figure out what is read from that drive, so I can move it? If not on Windows, can I do this on Linux?
This is also applicable for figuring out what files/folders a program is accessing in general, so I wouldn't say it only applies to my very narrow problem.
There's a simple tool called What's My Computer Doing? that you can use to get a quick idea of what's causing activity on your computer.
Install and run it, and leave it running in the background. Once you use this tool to narrow down which process is causing the disk activity, you'll want a more comprehensive tool. I use Process Monitor from Sysinternals/Microsoft.
It can be a bit daunting at first, but that's mainly because it is so powerful. It can also alter the behavior of the computer. When it's running, it backs up the huge quantity of data it collects to the disk. So that's why I suggest using the 'What's My Computer Doing?' tool first. Once you know which process is generating the disk access you can add a new filter rule (keep all the defaults, as they mask out a bunch of normal system processes) and select "Process Name" "is" "process_name", or select "PID" "is" "actual_PID".
There are plenty of tutorials like this one that can help you get started with Process Monitor.

Automatically force quit frozen applications in OSX maybe using a ruby script?

I built an application using openframeworks that is live 24/7 on a kiosk. Every now and then (every few weeks) it will randomly go unresponsive and I still can't get to the bottom of it because it's so random and infrequent it is hard to debug.
I wrote a ruby script that looks for the application running and if it doesn't exist it will start it up. This works in all cases where the application name doesn't show up in activity monitor. Meaning if the app crashes and completely force quits itself or something. It works just fine.
However, if the app just freezes and goes unresponsive (red highlight in activity monitor) the app doesn't quit out completely unless I force quit manually. Is there some kind of script I can write to look for all "unresponsive apps/processes" every few seconds and force quits them automatically? That way my app launcher script will be able to detect that the app isn't running and boot it up again.
I suggest you look at Monit because it's solid, well tested, well documented, and easy to learn.
If you still want to write your own monitoring script, Monit is a good example to follow.
The most reliable way to detect an unresponsive app is to have a "vital sign" which is a generic term for a signal that an app emit to prove it's healthy. Some people call this a "pulse" or "heartbeat" or "brainwave". Your external script watches the vital sign. If your external script sees the vital sign flatline, then the script takes action to cure the app or restart it.
An alternate way is to have a "ping" which is a generic term for your external script sending a signal to the app or the system, then listening for a reply. You can use tools such as the Unix ps command for processes, or AppleScript Activity Monitor. As far as I know, these do a pretty good job of catching common cases, but have trouble catching apps that are soaking up resources, such as being caught in endless loops.

Cocoa program can't be stopped

I'm trying to write an OS X app that uses a serial port. I found an example (cocoa) and got it running in Xcode 4. On the first run, it opens the port and I'm able to exchange data with the hardware.
If I try to change the port the program goes rogue. The pinwheel starts and the UI is unresponsive. I can't stop the program from Xcode, nor can I kill it from Terminal, or Force Quit. Force Quit of Xcode doesn't do it. Although the PID goes away with a kill from Terminal, the UI is still present with the merrily spinning pinwheel.
The only way out is a re-boot. Any ideas on how to track down the errant code are welcome. I'm new to Cocoa/Objective C, so simple terms are better.
Most likely it became a zombie. It should show up in ps auxww (or similar) with a 'Z' in its status. Activity Monitor might also still show it.
This is relatively common when working with hardware, such as a serial port. Zombies can arise for either of two reasons, most likely the first in this case:
The process is blocked in a kernel call of some kind, that's not interruptible.
The process has exited but its parent hasn't acknowledged that (via wait() or similar).
In the first case it's usually a fundamental bug or design flaw of some kind, and you may not have any good options short of figuring out exactly what code path tickles the problem, and avoiding that.
In the second case the solution is generally simple - find the parent process of your zombie and kill it. Repeat as necessary until your zombie gets adopted by a parent process that does call wait() to reap it (launchd will do this if nothing else).

Is there a way to detect and react to/stop a process from starting?

I'd like to have a program that just runs in the background and detects whenever a certain process is started and hopefully prevent it from starting and then react to it some way, in Windows. Specifically, my co-workers will install "epic fail" on anyone's machine who forgets to lock it for 2 seconds and gets coffee or goes to the restroom. I'd like to have a defense against this executable from running, and maybe have the computer say something like "no, you are the one that fails". I know certain root kits can do this, although obviously I'd not like to use something like this.
It's not hard to do, you can use EnumProcess or the Toolhelp API to get the processes, you could write a service to do this every so often and then kill the offending PID with TerminateProcess.

What happens to my app when my Mac goes to sleep?

When Mac OS X goes to sleep, due to closing a laptop or selecting "Sleep" from the Apple menu, how does it suspend an executing process?
I suppose non-windowed processes are simply suspended at an arbitrary point of execution. Is that also true for Cocoa apps, or does the OS wait until control returns to the run loop dispatcher, and goes to sleep in a "known" location? Does any modern OS do that, or is it usually safe enough to simply suspend an app no matter what it is doing?
I'm curious, because allowing sleep to occur at any moment means, from the app's perspective, the system clock could suddenly leap forward by a significant amount. That's a possibility I don't usually consider while coding.
Your app is interrupted exactly where it is that moment if the CPU is actually currently executing code of your app. Your app constantly gets execution time by the task scheduler, that decides which app gets CPU time, on which core, and for how long. Once the system really goes to sleep, the scheduler simply gives no time to your app any longer, thus it will stop execution wherever it is at that moment, which can happen pretty much everywhere. However, the kernel must be in a clean state. That means if you just made a call into the kernel (many libC functions do) and this call is not at some safe-point (e.g. sleeping, waiting for a condition to become true, etc.) or possibly holding critical kernel locks (e.g. funnels), the kernel may suspend sleep till this call returns back to user space or execution reaches such a safe-point before it finally cancels your app from the task scheduler.
You can open a kernel port and register for sleep/wake-up events. In that case, your app will receive an event, when the system wants to go to sleep. You have several possibilities. One is to reply to it, that the system may progress. Another one is to suspend sleep; however, Apple says certain events can be suspended at most 30 seconds, after that, the system will just continue, whether your app likes it or not. And finally, you can cancel it; though not all events can be canceled. If the system already decided it will go to sleep, you can only suspend this by at most 30 seconds or allow it at once, you cannot cancel it. However, you can also listen to an event, where the system asks apps, if it is okay to go to sleep now and there you can reply "no", causing a sleep to be canceled.
The difference between "Is it okay to sleep" and "I'm planing on going to sleep" is: The first one is sent if the power saving settings are applied, that is, if the user has not moved the mouse or typed anything for the time configured there. In that case the system will just ask, if sleep is okay. An app like Apple's DVD Player will say "no", because most likely the user watches a DVD and thus doesn't interact with the computer, still no reason to go to sleep. OTOH, if the user closes his Mac Book, apps are not asked, the system will go to sleep for sure and just informs apps, that have now up to 30 seconds to react to it.
Wake-up events can also be quite interesting to catch. E.g. if your system wakes up, open files might be inaccessible (an external drive has been unplugged) or network sockets won't work any longer (network has changed). So you may re-init certain app parts before using them and running into errors that are more or less expected.
Apple's page regarding catching these events.
It depends on your app.
If you are interacting with external systems (think networking or doing something over usb/firewire,etc) then it might be affected. An application running on OSX gets to run for a limited time ( max 10ms ) , after which it is interrupted by the kernel which schedules a new process from the process queue to run on the CPU. This is transparent for the application , which "thinks" that it runs all the time on the CPU. Thus , a transition to sleep is no different - apart from the time jumping ahead.
If you need to be aware that there was a transition to sleep mode please refer to this tech note which details how to receive notifications about the state change : Registering and unregistering for sleep and wake notifications
I believe it will just suspend all apps wherever they happen to be.
Remember, this happens all the time anyway. Applications are constantly suspended and resumed due to context switching. So, really, the clock could jump between any 2 instructions in your app, though usually not in a noticable/significant way.
If the OS waited for the app to return to some main loop you could run into situations where applications cause the sleep to hang. If they're doing a lot of work and not returning to the run loop dispatcher they would prevent the machine from going to sleep. That wouldn't be very good. :)
And if you set the time it also appears to leap forward to the running programs. Nothing special either.
Check out this Wikipedia article. Cavver is correct in stating that things like network connections may time out, and thus those services may be interrupted.

Resources