(Flutter/Dart) 如何在 Process.start 后终止进程

huangapple go评论71阅读模式
英文:

(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&lt;Process&gt; executeCommand(List&lt;String&gt; args) async {
  var process = await Process.start(&#39;java&#39;, 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 = &#39;${Platform.environment[&#39;JAVA_HOME&#39;]}\\bin&#39;;
var jps = Process.runSync(&#39;jps&#39;, [], workingDirectory: javaBinPath, runInShell: true);
for (var line in LineSplitter.split(jps.stdout)) {
  List&lt;String&gt; parts = line.split(&#39; &#39;);
  int pid = int.parse(parts[0]);
  String name = parts[1];
  if (name == &#39;x.jar&#39;) {
	Process.killPid(pid);
	break;
  }
}

It's an ugly solution, but it works.

huangapple
  • 本文由 发表于 2023年5月14日 01:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定