2011-03-26 75 views
0

在此先感謝任何幫助我的人。CFRunLoopRun()和NSTimer - >分段錯誤

我有一個簡單的守護進程。我分配一個類,然後開始計劃&重複的NSTimer:

[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(usage3GviaSysctl) userInfo:nil repeats:YES]; 

然後我打電話CFRunLoopRun(),使我的守護進程會活下去。

int main(int argc, char *argv[]) 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    signal(SIGTERM, (sig_t)SIGTERM_handler); 

    helper = [[NMDaemonHelper alloc] init]; 
    [helper startNotificationServer]; 
    CFRunLoopRun(); 

    NSLog(@"NMDAEMON: will exit"); 
    [pool release]; 
    return 0; 
} 

現在的問題是,定時器啓動後,我得到一個段錯誤。 BT:

objc_msgSend 
__NSFireTimer 
__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ 
__CFRunLoopDoTImer 
__CFRunLoopRun 
CFRunLoopRunSpecific 

其他方法來啓動定時器也不能工作。例如:

NSTimer *timeUpdateTimer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(usage3GviaSysctl) userInfo:nil repeats:YES]; 
[[NSRunLoop currentRunLoop] addTimer:timeUpdateTimer forMode:NSDefaultRunLoopMode]; 

有沒有人知道(g)上發生了什麼事(wr)?

回答

0

我的猜測是你的選擇器沒有正確的格式......需要有一個NSTimer參數,所以你的選擇器必須在其中有「:」,所以@selector(usage3GviaSysctl :)。

...我沒有嘗試過自己,似乎工作所以這裏是我的代碼的情況下,這是別的東西:

#import <Foundation/Foundation.h> 

@interface NMDaemonHelper : NSObject { 
    NSTimer *_aTimer; 
} 
- (void)startNotificationServer; 
@end 

@implementation NMDaemonHelper 

- (void)dealloc { 
    [_aTimer invalidate]; 
    [super dealloc]; 
} 

- (void)startNotificationServer { 
    _aTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(usage3GviaSysctl:) userInfo:nil repeats:YES]; 
} 

- (void)usage3GviaSysctl:(NSTimer *)aTimer { 
    NSLog(@"timer fired"); 
} 

@end 

void SIGTERM_handler(int signum) { 
    NSLog(@"SIGTERM_handler"); 
} 

int main(int argc, char *argv[]) { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    signal(SIGTERM, (sig_t)SIGTERM_handler); 

    NMDaemonHelper *helper = [[NMDaemonHelper alloc] init]; 
    [helper startNotificationServer]; 
    CFRunLoopRun(); 

    [helper release]; 
    NSLog(@"NMDAEMON: will exit"); 
    [pool release]; 
    return 0; 
} 

...和輸出是:

pho0 $ ./climac
2011-03-25 18:43:36.723 climac [2833:903]定時器發射
2011-03-25 18:43:39.723 climac [2833:903]定時器發射
2011-03-25 18:43: 42.722 climac [2833:903]定時器發射
2011-03-25 18:43:45.722 climac [2833:903]定時器開火
2011-03-25 18:43:48.722 climac [2833:903] timer fired
2011-03-25 18:43:51.722 climac [2833:903] timer fired

+0

注意:您的'dealloc'永遠不會被調用 - 請參閱_ [使用定時器:內存管理](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Timers/Articles/usingTimers的.html#// apple_ref/DOC/UID/20000807-SW6)_。 – danyowdee 2011-03-26 13:35:04

+0

謝謝你試圖幫助我。實際上,我發現這並不是因爲NSTimer而發生的,而是因爲在定時器的action方法中使用了sysctl。這是無法識別的,因爲碰撞記者會創建一個錯誤的bt :( – YllierDev 2011-03-27 19:33:39

+0

@danyowdee,dealloc在那裏使這個完整的實現。這是一個人爲的例子,但如果你真的使用類,你會 – pho0 2011-07-19 07:21:46