stop method

Future<void> stop({
  1. bool force = false,
})

Stops the managed process gracefully.

If the process is not running, this method returns without taking any action. Otherwise, it:

  1. Sends SIGTERM to the process
  2. Waits up to 5 seconds for graceful shutdown
  3. If still running, sends SIGKILL to force termination
  4. Cleans up all resources and sets status to ProcessStatus.absent

This method is safe to call multiple times.

Calling with force true skips the SIGTERM signal and the gradeful wait period.

Implementation

Future<void> stop({bool force = false}) async {
  if (_status != ProcessStatus.running && _status != ProcessStatus.starting) {
    return;
  }

  _updateStatus(ProcessStatus.stopping);
  _logWriter((pid: _process?.pid, isError: false, text: 'Stopping process'));

  if (_process != null) {
    try {
      _process!.kill(force ? ProcessSignal.sigkill : ProcessSignal.sigterm);

      var resultFuture = _process!.exitCode;
      if (!force) {
        resultFuture = resultFuture.timeout(
          Duration(seconds: force ? 0 : 5),
          onTimeout: () {
            _logWriter((
              pid: _process?.pid,
              isError: false,
              text: 'Force killing process',
            ));
            _process!.kill(ProcessSignal.sigkill);
            return _process!.exitCode;
          },
        );
      }
      final result = await resultFuture;

      _logWriter((
        pid: _process?.pid,
        isError: false,
        text: 'Process stopped with exit code: $result',
      ));
    } catch (e) {
      _logWriter((
        pid: _process?.pid,
        isError: true,
        text: 'Error stopping process: $e',
      ));
    }
  }

  await _cleanup();
  _updateStatus(ProcessStatus.absent);

  if (_stopCompleter != null && !_stopCompleter!.isCompleted) {
    _stopCompleter!.complete();
  }
}