diff --git a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm index 38b39dd..ba5de76 100644 --- a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm +++ b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm @@ -5,6 +5,7 @@ #import "EngineMessenger.h" #import "../Engines/AvailableEngines.h" +#include @implementation EngineMessenger : NSObject @@ -25,7 +26,8 @@ - (id)initWithEngineType: (EngineType_objc) type { self = [super init]; if (self) { - _lock = [[NSLock alloc] init]; + signal(SIGPIPE, SIG_IGN); + _lock = [[NSLock alloc] init]; switch (type) { case EngineTypeStockfish: _engine = new StockfishEngine(); @@ -83,23 +85,53 @@ - (void)start { - (void)stop { [_lock lock]; - [_pipeReadHandle closeFile]; - [_pipeWriteHandle closeFile]; - _readPipe = NULL; - _pipeReadHandle = NULL; + // Remove read notifications before closing any handles + if (_pipeReadHandle) { + [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadCompletionNotification object:_pipeReadHandle]; + } + + // Close write side first to signal EOF to the reader and avoid further writes + if (_pipeWriteHandle) { + @try { + [_pipeWriteHandle closeAndReturnError:nil]; + } @catch (NSException *exception) { + NSLog([exception description]); + } + } - _writePipe = NULL; - _pipeWriteHandle = NULL; + _pipeWriteHandle = nil; + _writePipe = nil; + + // Close read side + if (_pipeReadHandle) { + @try { + [_pipeReadHandle closeAndReturnError:nil]; + } @catch (NSException *exception) { + NSLog([exception description]); + } + } + + _pipeReadHandle = nil; + _readPipe = nil; - [[NSNotificationCenter defaultCenter] removeObserver:self]; [_lock unlock]; } - (void)sendCommand: (NSString*) command { dispatch_sync(_queue, ^{ - const char *cmd = [[command stringByAppendingString:@"\n"] UTF8String]; - write([_pipeWriteHandle fileDescriptor], cmd, strlen(cmd)); + if (!_pipeWriteHandle) { return; } + NSString *line = [command stringByAppendingString:@"\n"]; + NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding]; + + if (!data) { return; } + + ssize_t fd = [_pipeWriteHandle fileDescriptor]; + + if (fd < 0) { return; } + + ssize_t result = write(fd, [data bytes], [data length]); + (void)result; }); }