终止NSTask及其子节点 [英] Terminate an NSTask and its children
问题描述
我使用NSTask执行一系列长时间运行的命令,如:
commandToRun = command2;
NSArray * arguments = [NSArray arrayWithObjects:
@ - c,
commandToRun,
nil];
self.task = [[NSTask alloc] init];
[self.task setLaunchPath:@/ bin / sh];
[self.task setArguments:arguments];
[self.task launch];
这会为shell创建一个进程,并为当前运行的命令创建一个子进程命令1或命令2)。如果我用 [self.task terminate]
杀死任务,它只会杀死父进程。有什么方法来识别和杀死孩子吗?
这不是很优雅,但你可以 sh
子任务作为后台进程,然后使用shell变量 $!
按照这里,阻塞直到每个后台进程完成以保持异步:
commandToRun = @command1& echo $!> / tmp / childpid; wait $ !; command2& echo $!> / tmp / childpid; wait $!;
然后当您调用 [self.task terminate]
您还应该调用:
系统(kill -9` cat / tmp / childpid`);
I'm using NSTask to execute a series of long running commands like so:
commandToRun = @"command 1;command2"; NSArray *arguments = [NSArray arrayWithObjects: @"-c", commandToRun, nil]; self.task = [[NSTask alloc] init]; [self.task setLaunchPath: @"/bin/sh"]; [self.task setArguments: arguments]; [self.task launch];
This creates a process for the shell, and a child process for whichever command is running at the time (command 1 or command 2). If I kill the task with
[self.task terminate]
it only kills the parent process. Is there a way to identify and kill the children too?解决方案It's not exactly elegant, but you can make
sh
launch the subtasks as background processes and then write their PIDs to a file using the shell variable$!
as per here, blocking till each background process completes to maintain asynchronicity:commandToRun = @"command1 & echo $! > /tmp/childpid; wait $!; command2 & echo $! > /tmp/childpid; wait $!";
Then when you call
[self.task terminate]
you should also invoke:system("kill -9 `cat /tmp/childpid`");
...or something equivalent.
这篇关于终止NSTask及其子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!