Do processes have a chance to terminate safely after wsl.exe --terminate?

Viewed 294

Do processes have a chance to terminate safely when the user calls wsl.exe --terminate or wslconfig.exe /t to terminate a distribution on WSL? I'd also like to understand if there's any difference between WSL2 and WSL1 in this respect. On linux, my understanding is that shutdown(8) sends SIGTERM to all processes, which gives them a chance to save and exit cleanly. Is this the case in WSL too through the terminate commands?

1 Answers

For anyone coming here, there appears to be no clear documentation on what the terminate commands do under the hood, but based on a little experimentation I don't believe they send any signals to the processes, and the behaviour is the same for WSL1 and WSL2.

Here's some sample code to trap SIGTERM (can be modified for any signal).

#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

static volatile sig_atomic_t sigterm_flag = 0;

static void sigterm_handler(int _)
{
  (void)_;
  sigterm_flag = 1;
}

int main(void)
{
  signal(SIGTERM, sigterm_handler);

  while (1) {
    if (sigterm_flag) {
      puts("Terminated by SIGTERM");
      break;
    }
    sleep(1);
    puts("Still running...");
  }
  return EXIT_SUCCESS;
}

I compiled this and ran it. Then I ran wsl.exe --terminate or wslconfig.exe /t or wsl --shutdown from a separate powershell tab. No signals are trapped by the program and the WSL instance simply exits. Sending signals directly using kill works as expected and prints the trapped signal before exiting.

If anyone can shed some light on what actually happens when you call --terminate that would be useful. Also, thanks to this post for some help.

Related