用于启动包括参数和环境变量在内的独立进程的一个很好的类是 NSTask。有关详细信息,请参阅文档。这是一个小命令行工具,它启动 10 个并发进程并等待它们完成。NSOperationQueue 在这里是多余的,因为任务已经同时启动。
-- 编辑:有限并发的改进版本 --
int main (int argc, const char * argv[])
{
@autoreleasepool {
// Let's not have more than 5 parallel processes
dispatch_semaphore_t limit = dispatch_semaphore_create(5);
dispatch_semaphore_t done = dispatch_semaphore_create(0);
for (int i=0; i<10; i++) {
// Setup the taks as you see fit including the environment variables.
// See docs on NSTask for more on how to use this object.
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/ls";
task.arguments = [NSArray arrayWithObject:@"-la"];
task.terminationHandler = ^(NSTask *task) {
dispatch_semaphore_signal(limit);
if (i==9) dispatch_semaphore_signal(done);
};
dispatch_semaphore_wait(limit, DISPATCH_TIME_FOREVER);
[task launch];
}
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
dispatch_release(limit);
dispatch_release(done);
}
return 0;
}
-- 原版 --
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSObject *lock = [[NSObject alloc] init];
int __block counter = 10;
for (int i=0; i<10; i++) {
// Setup the taks as you see fit including the environment variables.
// See docs on NSTask for more on how to use this object.
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/ls";
task.arguments = [NSArray arrayWithObject:@"-la"];
task.terminationHandler = ^(NSTask *task) {
@synchronized(lock) { counter--; }
};
[task launch];
}
while (counter)
usleep(50);
[lock release];
}
return 0;
}
在您的情况下,您可能希望将 NSTask 对象保存在数组中以便于管理。