Timmmm
Timmmm

Reputation: 96832

Dart Process.kill has no effect

I have the following code that starts webdev serve, waits for it to be ready and then tries to kill it.

import 'dart:async';
import 'dart:io';
import 'package:async/async.dart' show StreamGroup;

void main(List<String> arguments) async {

  var stdout0 = StreamController<List<int>>();
  var stdout1 = StreamController<List<int>>();
  var stderr0 = StreamController<List<int>>();
  var stderr1 = StreamController<List<int>>();

  stdout.addStream(StreamGroup.merge([stdout0.stream, stdout1.stream]));
  stderr.addStream(StreamGroup.merge([stderr0.stream, stderr1.stream]));

  print('Starting webdev');
  var webdev = await Process.start('webdev', ['serve', '--auto', 'refresh']);
  stdout0.addStream(webdev.stdout);
  stderr0.addStream(webdev.stderr);

  // Wait for localhost:8080 to be accessible.
  print('Waiting for webdev');

  var timer = Timer(Duration(seconds: 20), () {});
  for (;;) {
    try {
      Socket socket = await Socket.connect('127.0.0.1', 8080, timeout: Duration(seconds: 1));
      socket.close();
      break;
    } catch (SocketException) {
    }
    if (!timer.isActive) {
      throw Exception('Couldn\'t connect to 127.0.0.1:8080');
    }
    await Future.delayed(Duration(seconds: 1));
  }

  print('Killing webdev');
  webdev.kill(ProcessSignal.sigkill);
}

However webdev.kill() doesn't seem to do anything. I've tried various signals, and nothing has any effect, and it also returns true every time. Even weirder, if I run kill -s TERM <pid> in another terminal to kill the process, it does die, but my Dart program doesn't seem to realise - at least it doesn't exit. What's going on?

Upvotes: 2

Views: 1072

Answers (2)

Simone Mariottini
Simone Mariottini

Reputation: 125

Still experiencing the same issue in 2025, I fixed with this workaround that kills the entire tree:

 // Kill process tree on Windows
final killTree = await Process.run('taskkill', ['/F', '/T', '/PID', '${process.pid}']);

Upvotes: 0

Timmmm
Timmmm

Reputation: 96832

This turned out to be a bug in Dart. Basically the problem is that webdev serve starts a child process that actually does the serving. When you call Process.kill() it only kills the parent process, and the child process is left running.

By the way a good way to diagnose this is to run htop -t and then press F4 to filter the processes you want.

Upvotes: 1

Related Questions