我附在我的 C 文件 beforesleep.c 的内容下方,当收到“将睡眠”通知时,它会执行一些命令行命令(在我的例子中是 shell 命令和 AppleScript 脚本)。
您可以将代码放在哪里:
为了在 mac 进入休眠状态时运行您的代码,只需将 system(...) 调用替换为您希望运行的代码即可。
在我的例子中,我使用system(),因为它允许我运行以字符串形式传递的 shell 命令,但如果您更喜欢只运行 C 代码,则可以将 C 代码放在那里。
如何构建它
为了构建这个文件,我运行:
gcc -framework IOKit -framework Cocoa beforesleep.c
备注
如果您要使用此代码,请确保它始终在后台运行。例如,我有一个 Cron 作业,它确保此代码始终运行,并再次启动它,以防它因任何原因被意外杀死(尽管到目前为止它从未发生在我身上)。如果您有足够的经验,您可以找到更聪明的方法来确保这一点。
更多信息
有关其工作原理的更多详细信息,请参阅this link(已由 sidyll 建议)。
代码模板
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <mach/mach_port.h>
#include <mach/mach_interface.h>
#include <mach/mach_init.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
io_connect_t root_port; // a reference to the Root Power Domain IOService
void
MySleepCallBack( void * refCon, io_service_t service, natural_t messageType, void * messageArgument )
{
switch ( messageType )
{
case kIOMessageCanSystemSleep:
IOAllowPowerChange( root_port, (long)messageArgument );
break;
case kIOMessageSystemWillSleep:
system("/Users/andrea/bin/mylogger.sh");
system("osascript /Users/andrea/bin/pause_clockwork.scpt");
IOAllowPowerChange( root_port, (long)messageArgument );
break;
case kIOMessageSystemWillPowerOn:
//System has started the wake up process...
break;
case kIOMessageSystemHasPoweredOn:
//System has finished waking up...
break;
default:
break;
}
}
int main( int argc, char **argv )
{
// notification port allocated by IORegisterForSystemPower
IONotificationPortRef notifyPortRef;
// notifier object, used to deregister later
io_object_t notifierObject;
// this parameter is passed to the callback
void* refCon;
// register to receive system sleep notifications
root_port = IORegisterForSystemPower( refCon, ¬ifyPortRef, MySleepCallBack, ¬ifierObject );
if ( root_port == 0 )
{
printf("IORegisterForSystemPower failed\n");
return 1;
}
// add the notification port to the application runloop
CFRunLoopAddSource( CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes );
/* Start the run loop to receive sleep notifications. Don't call CFRunLoopRun if this code
is running on the main thread of a Cocoa or Carbon application. Cocoa and Carbon
manage the main thread's run loop for you as part of their event handling
mechanisms.
*/
CFRunLoopRun();
//Not reached, CFRunLoopRun doesn't return in this case.
return (0);
}