英文:
(Flutter/Dart) How to kill process after Process.start
问题
我有这个 Future 函数:
Future<Process> executeCommand(List<String> args) async {
var process = await Process.start('java', args, workingDirectory: folder);
return process;
}
process = await ref.read(searchControllerProvider).executeCommand(cmd);
await stdout.addStream(process.stdout);
它应该执行一个命令来运行一个jar文件。如何在进程结束之前添加一个按钮来终止进程?Process.killPid(process.pid)
和 process.kill()
都不起作用。killPid
在我点击按钮的第一次时返回 true
,但进程仍在运行。
英文:
I have this Future function:
Future<Process> executeCommand(List<String> args) async {
var process = await Process.start('java', args, workingDirectory: folder);
return process;
}
process = await ref.read(searchControllerProvider).executeCommand(cmd);
await stdout.addStream(process.stdout);
It's supposed to execute a command to run a jar file. How do I add a button to kill the process before it ends? Neither Process.killPid(process.pid)
nor process.kill()
is working. killPid
returns true
the first time I click the button, but it's still running.
答案1
得分: 0
这更像是一个jar文件的问题,而不是Dart/Flutter的问题。
Dart使用process.pid
返回的pid
并不是jar文件所使用的正确pid
。
最终,我运行了Java的jps
命令,并循环遍历输出以搜索正确的pid
。
String javaBinPath = '${Platform.environment['JAVA_HOME']}\\bin';
var jps = Process.runSync('jps', [], workingDirectory: javaBinPath, runInShell: true);
for (var line in LineSplitter.split(jps.stdout)) {
List<String> parts = line.split(' ');
int pid = int.parse(parts[0]);
String name = parts[1];
if (name == 'x.jar') {
Process.killPid(pid);
break;
}
}
这是一个不太美观的解决方案,但它能够工作。
英文:
This was more of a jar problem and not a Dart/Flutter one.
The pid
that Dart gives with process.pid
is not the correct one which is used by the jar file.
I ended up running Java's jps
command and looping through the output to search for the correct pid.
String javaBinPath = '${Platform.environment['JAVA_HOME']}\\bin';
var jps = Process.runSync('jps', [], workingDirectory: javaBinPath, runInShell: true);
for (var line in LineSplitter.split(jps.stdout)) {
List<String> parts = line.split(' ');
int pid = int.parse(parts[0]);
String name = parts[1];
if (name == 'x.jar') {
Process.killPid(pid);
break;
}
}
It's an ugly solution, but it works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论