在Mac OSX上接收电源通知(尤其是关机)

bin*_*bob 8 c macos shutdown

我正在用C编写一个用于Mac(Leopard)的应用程序,它需要在接收电源通知时做一些工作,例如睡眠,唤醒,关机,重启.它launchd在登录时作为启动运行,然后开始监视通知.我用来做这个的代码如下:

/* ask for power notifications */
static void StartPowerNotification(void)
{
    static io_connect_t rootPort;   
    IONotificationPortRef notificationPort;
    io_object_t notifier;

    rootPort = IORegisterForSystemPower(&rootPort, &notificationPort, 
                                        PowerCallback, &notifier);
    if (!rootPort) 
        exit (1);

    CFRunLoopAddSource (CFRunLoopGetCurrent(),  
                        IONotificationPortGetRunLoopSource(notificationPort), 
                        kCFRunLoopDefaultMode);
}

/* perform actions on receipt of power notifications */
void PowerCallback (void *rootPort, io_service_t y, 
                    natural_t msgType, void *msgArgument)
{
    switch (msgType) 
    {
        case kIOMessageSystemWillSleep:
            /* perform sleep actions */
            break;

        case kIOMessageSystemHasPoweredOn:
            /* perform wakeup actions */
            break;

        case kIOMessageSystemWillRestart:
            /* perform restart actions */
            break;

        case kIOMessageSystemWillPowerOff:
            /* perform shutdown actions */
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,只为睡眠和唤醒(前两名kIOMessageSystemWillSleepkIOMessageSystemHasPoweredOn)曾经被调用.我从来没有得到重启或关机(kIOMessageSystemWillRestartkIOMessageSystemWillPowerOff)的任何通知.

难道我做错了什么?或者是否有其他API可以提供重启和关机通知?我更喜欢把它作为一个C程序(就像我熟悉的那样)但是对任何合理的替代建议都持开放态度(我已经看过登录/注销钩子了但这些看起来似乎不赞成了发射).

在此先感谢您的任何帮助/提示!

Rob*_*ger 6

我知道您可以从NSWorkspace注册NSWorkspaceWillPowerOffNotification通知,它不是C函数,但确实可以工作。

#import <AppKit/AppKit.h>
#import "WorkspaceResponder.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter];
    WorkspaceResponder *mainController = [[WorkspaceResponder alloc] init];

    //register for shutdown notications
    [nc addObserver:mainController
selector:@selector(computerWillShutDownNotification:)
          name:NSWorkspaceWillPowerOffNotification object:nil];
    [[NSRunLoop currentRunLoop] run];
    [pool release];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后在WorkspaceResponder.m中:

- (void) computerWillShutDownNotification:(NSNotification *)notification {
    NSLog(@"Received Shutdown Notification");
}
Run Code Online (Sandbox Code Playgroud)