Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 42 additions & 10 deletions Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#import "EngineMessenger.h"
#import "../Engines/AvailableEngines.h"
#include <signal.h>

@implementation EngineMessenger : NSObject

Expand All @@ -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();
Expand Down Expand Up @@ -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;
});
}

Expand Down