flutter中Process.start执行命令后,kill对应进程

问题类似这个:https://stackoverflow.com/questions/76244179/flutter-dart-how-to-kill-process-after-process-start

我在flutter中用dart:io库中的Process.start执行一个命令行后,怎么也无法删除,尝试用dart给的process的pid,再kill掉,发现所给的并不是正确的pid,故此,我通过ps -a得出当前正在执行的所有进程信息,kill掉所指定的进程。

这里只给出最简单的例子,其他特判情况需要另外作处理,首先,我再flutter程序的某个地方执行了命令开启一个python的标准文件服务器,相关代码如下:

import 'dart:io';

late Process process;
process = await Process.start('python3', ['-m', 'http.server', '8090'], workingDirectory: "${Constant.pkgDir}$devType/");

这里我单独写了一个函数去关掉这个python的进程,因为在我的业务逻辑中,这个命令需要多次不同的执行,函数如下:

void killFileServer() async{
  process = await Process.start('ps', ['-a']);
  String pidPython = "";
  // 读取标准输出
  process.stdout.transform(utf8.decoder).listen((data) {
    print(data);
    List<String> stdoutLines = data.split('\n');
    for (int i=0;i<stdoutLines.length; i++) {
      if(stdoutLines[i].split(' ').last == 'python3'){
        pidPython = stdoutLines[i].split(' ').first;
        print(">>>>pid of python3: ${stdoutLines[i].split(' ').first}");
        Process.start('kill', ['-9', pidPython]);
      }
    }
  });
  // 等待进程结束
  await process.exitCode;
}

注:这个函数的大致逻辑,是让其找到python对应进程的进程号,然后把他kill掉。

你可能感兴趣的:(flutter,flutter)