gpt4 book ai didi

objective-c - 进程间通信使用NSPipe,NSTask

转载 作者:太空狗 更新时间:2023-10-30 03:44:34 25 4
gpt4 key购买 nike

我需要使用 NSPipe channel 实现两个线程之间的通信,问题是我不需要通过指定此方法来调用终端命令。

[task setCurrentDirectoryPath:@"....."];
[task setArguments:];

我只需要写一些数据

NSString * message = @"Hello World";
[stdinHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];

在另一个线程上接收这个消息

NSData *stdOutData = [reader availableData];
NSString * message = [NSString stringWithUTF8String:[stdOutData bytes]]; //My Hello World

例如,在 C# 中,使用 NamedPipeClientStream、NamedPipeServerStream 类可以轻松完成此类操作,其中管道由 id 字符串注册。

如何在Objective-C中实现?

最佳答案

如果我正确理解你的问题,你可以创建一个 NSPipe 并使用一端读取和写入一端。示例:

// Thread function is called with reading end as argument:
- (void) threadFunc:(NSFileHandle *)reader
{
NSData *data = [reader availableData];
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", message);
}

- (void) test
{
// Create pipe:
NSPipe *pipe = [[NSPipe alloc] init];
NSFileHandle *reader = [pipe fileHandleForReading];
NSFileHandle *writer = [pipe fileHandleForWriting];

// Create and start thread:
NSThread *myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(threadFunc:)
object:reader];
[myThread start];

// Write to the writing end of pipe:
NSString * message = @"Hello World";
[writer writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];

// This is just for this test program, to avoid that the program exits
// before the other thread has finished.
[NSThread sleepForTimeInterval:2.0];
}

关于objective-c - 进程间通信使用NSPipe,NSTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com