Windows interface for linux

Время на прочтение6 мин

Количество просмотров106K

Раньше моей рабочей машиной был ноутбук, созданный Apple. Я мог делать на нём практически всё что угодно: разрабатывать программы, писать тексты, сочинять музыку, да и много чего ещё. Но мне не давали покоя мысли о том, что я привязан к экосистеме Apple, о том, что я зависим от прихотей этой компании. Поэтому я приступил к поискам чего-то нового.

Я начал собирать рабочую станцию под задачи машинного обучения. Поставил в неё, кроме прочего, отличный процессор, много памяти, достойную видеокарту. Практически все мои задачи я решал в Ubuntu. Правда, для работы с текстами мне нужен был Microsoft Office. Онлайновый Office тогда ещё не появился, и, давайте называть вещи своими именами, LibreOffice — это просто ужас какой-то. Для меня решением стала двойная загрузка в конфигурации Ubuntu — Windows 10. Мне невероятно понравилось то ощущение свободы, которое испытываешь, переходя с ОС от Apple на Ubuntu. А возможности, которые открываются перед тем, кто сам собирает свой компьютер, практически бесконечны.

Двойная загрузка в течение долгого времени полностью меня устраивала. А когда я миллион раз ей воспользовался, появилась технология WSL (Windows Subsystem for Linux, подсистема Windows для Linux). Когда это случилось, я начал решать некоторые свои Linux-задачи в Windows. Правда, даже так, многого для полноценной работы мне ещё не хватало. Но теперь, с выходом WSL 2, у меня возникает такое ощущение, что новая версия WSL способна кардинальным образом изменить ситуацию. Сегодня я предлагаю поговорить о том, как, с помощью WSL 2, перенести задачи по разработке программ из Linux в Windows 10. Я расскажу о новых возможностях WSL 2, и о том, что можно ожидать от этой подсистемы в будущем.

Обзор WSL 2

WSL 2 — это новая версия подсистемы Windows для Linux. В этой версии имеются некоторые изменения, определяющие то, как Linux-дистрибутивы взаимодействуют с Windows.

Microsoft любит Linux

В этом релизе WSL в распоряжении пользователя оказывается улучшенная производительность файловой системы и полная совместимость с системными вызовами. Конечно, у нас есть возможность запускать Linux либо на WSL 1, либо на WSL 2, и, более того, переключаться между разными версиями WSL можно в любое время. WSL 2 — это результат серьёзного усовершенствования базовой архитектуры системы, её новые возможности основаны на технологии виртуализации и на функционале ядра Linux. При этом Microsoft берёт на себя заботу о мелких деталях, поэтому пользователь WSL может просто заниматься своими делами, ни на что не отвлекаясь.

Установка

Microsoft обещает, что в ближайшем будущем установка WSL 2 будет выполняться очень просто, и что Linux можно будет обновлять с использованием механизма обновлений Windows. Пока же процесс установки WSL 2 требует некоторых усилий, но, на самом деле, ничего страшного тут нет.

В этом примере мы установим на Windows 10 Ubuntu 20.04. Надо отметить, что процесс установки будет одним и тем же для всех дистрибутивов Linux, доступных в Microsoft Store. Для начала нужно включить компонент Windows Subsystem for Linux. Для этого надо открыть PowerShell от имени администратора и выполнить следующую команду:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Далее, нужно обновить WSL до WSL 2. Для этого Windows 10 должна быть обновлена до версии 2004. В BIOS должна быть включена технология виртуализации Intel. Снова воспользуемся PowerShell с административными привилегиями и выполним такую команду:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Для завершения установки WSL и обновления до WSL 2 перезагрузите компьютер. Затем нужно установить WSL 2 в качестве версии WSL, используемой по умолчанию при установке новых дистрибутивов Linux. Для этого, всё так же, пользуясь PowerShell с правами администратора, выполним эту команду:

wsl --set-default-version 2

После того, как вы выполните эту команду, может появиться такое сообщение:

WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel

Сообщение, выдаваемое при попытке установки WSL 2 как подсистемы Windows для Linux, используемой по умолчанию

Перейдите по указанной ссылке и установите соответствующий MSI-файл, благодаря которому на вашу машину будет установлено ядро Linux для WSL 2. После того, как ядро будет установлено, выполните вышеприведённую команду снова. Теперь она должна завершиться успешно, не выдавая подобного сообщения.

Теперь осталось лишь установить нужный дистрибутив Linux. Для этого надо открыть Microsoft Store и поискать там Ubuntu 20.04 LTS. После установки дистрибутива в меню Пуск должен появиться ярлык для запуска Ubuntu. Запустите систему и следуйте инструкциям для завершения установки (в целом, завершение установки заключается в создании нового пользователя).

Для того чтобы проверить, действительно ли дистрибутив установлен на WSL 2, выполните такую команду:

wsl --list --verbose

Если оказалось, что используется WSL 1, то переключиться на WSL 2 можно, воспользовавшись командой такого вида:

wsl --set-version <distribution name> <versionNumber>

Вот и всё. Теперь в вашем распоряжении имеется полноценный дистрибутив Ubuntu, работающий в Windows 10.

Настройка рабочей среды для программиста

Теперь, когда в вашем распоряжении оказалась рабочая Ubuntu, вы можете устанавливать всё, что вам может понадобиться. Например, если вы — дата-сайентист, вы можете установить самый свежий дистрибутив Anaconda. Если вы — фронтенд-разработчик, то вас, например, могут заинтересовать Angular, npm и многое другое. Здесь же мне хотелось бы сосредоточиться на двух инструментах. Это — Visual Studio Code и связка Docker + Kubernetes.

▍Visual Studio Code

VS Code — это редактор кода, которому отдаёт предпочтение множество разработчиков. Одна из сильных сторон этого редактора заключается в поддержке бесконечного множества расширений. А теперь, когда мы включили WSL 2, совершенно необходимым расширением для VS Code можно назвать Remote Development.

Это расширение позволяет удалённо работать над кодом, который имеется в среде, создаваемой средствами WSL 2, в контейнере, или даже на удалённой виртуальной машине, доступ к которой осуществляется по SSH. Данное расширение позволяет, например, создать проект в ОС Linux, работающей в WSL 2, и использовать для работы над этим проектом редактор VS Code, установленный в Windows 10.

Собственно говоря, VS Code отличается огромными возможностями. Это и интеллектуальная система IntelliSense, и интеграция с git, и отладчик, и терминал, и очень много чего ещё. Полагаю, с настройкой VS Code вы справитесь и очень скоро сможете сделать из этого редактора именно то, что нужно вам.

▍Docker + Kubernetes

Docker для Windows сделан на «хорошо», но не на «отлично». На самом деле, именно Docker заставлял меня постоянно «прыгать» между Windows и Ubuntu. Например, мне приходилось делать это тогда, когда нужно было создать новый образ Docker. А вот WSL 2 отличается полной поддержкой Docker. Это, полагаю, такая возможность новой подсистемы, которая делает работу с Docker даже удобнее, чем в Linux.

Для того чтобы включить эту возможность, нужно перейти в настройки Docker Desktop и включить опцию Use the WSL 2 based engine.

Включение поддержки Docker для WSL 2

Более того, перейдя в раздел настроек Kubernetes, можно включить возможность запуска локального кластера Kubernetes, просто установив соответствующий флажок.

Включение Kubernetes

Теперь можно перезапустить Ubuntu в WSL 2 и выполнить следующие команды:

docker version 
kubectl version

Результаты выполнения подобных команд покажут, что в вашем распоряжении теперь есть Docker и Kubernetes.

Docker и Kubernetes работают в среде WSL 2

Бонус: новый терминал Windows

В качестве дополнительной полезной программы вы можете установить из Microsoft Store новый терминал Windows. В описании к нему сказано, что перед нами новое современное приложение — быстрое, эффективное и мощное. Оно предназначено для пользователей, работающих с инструментами командной строки и с соответствующими средами, наподобие PowerShell. Среди его главных возможностей можно отметить следующие: поддержка вкладок и панелей, поддержка Unicode и UTF-8, ускорение вывода текста средствами GPU, поддержка пользовательских тем, стилей и настроек.

Вот видео про новый терминал Windows.

Более того, новый терминал очень хорошо выглядит, а его внешний вид поддаётся настройке. Настройки можно выполнять, пользуясь особым JSON-файлом. Здесь можно найти темы для терминала. Вот материал, в котором можно почитать подробности о терминале.

Планы развития WSL

В WSL 2 ещё недостаёт некоторых возможностей, но подсистема Windows для Linux развивается в правильном направлении. В ближайшее время установить WSL можно будет с помощью одной команды. Для этого достаточно будет открыть терминал Windows и выполнить в нём следующее:

wsl.exe --install

Кроме того, WSL 2 будет той версией подсистемы, которая, при первой установке WSL, устанавливается по умолчанию.

Надо отметить, что разработчики очень ждут от WSL следующих возможностей: поддержка видеокарт и поддержка приложений с графическим интерфейсом.

С момента выхода WSL 1 команду разработчиков этой подсистемы чаще всего просили о внедрении в WSL поддержки CUDA или GPU Compute. В последний код команды разработчиков WSL, систем виртуализации, DirectX, Windows Driver работают над этой возможностью. Поэтому — следите за новостями.

Обучение модели, использующей технологии глубокого обучения, в WSL 2 (с использованием CUDA)

Более того, на подходе и поддержка графических приложений для Linux. Например, в Linux-системах, установленных на WSL, можно будет пользоваться текстовыми редакторами или IDE. На Windows-машине можно будет даже разрабатывать GUI-приложения для Linux!

Поддержка графического интерфейса Linux в WSL 2

Итоги

Сегодня мы поговорили о том, как, пользуясь WSL 2 можно превратить Windows-компьютер в рабочую станцию программиста, пользующегося Linux. В распоряжении такого программиста оказывается высокая производительность и множество полезных возможностей, набор которых, со временем, пополнится. Поэтому я и могу говорить о том, что двойная загрузка умерла.

А вы пользуетесь WSL 2?

Среда Windows Subsystem for Linux (WSL) позволяет запускать нативные приложения, писать скрипты, выполнять команды и скрипты Linux непосредственно из Windows без использования эмуляторов или развертывания выделенных виртуальных машин. Актуальной версией среды является WSL 2, в которой используется полноценное ядро Linux (версия ядра 5.15) и обеспечивает полную совместимость с системными вызовами. Образ ядра Linux в WSL представляет собой легкую виртуальную машину, для запуска которой не нужно устанавливать полноценную роль Hyper-V.

Содержание:

  • Как установить Windows Subsystem for Linux (WSL2)?
  • WSL: Установка дистрибутива Linux в Windows
  • Команды для управления WSL в Windows
  • Использование Linux в среде WSL

Вы можете запустить WSL 2:

  • Во всех версиях Windows 10, начиная с 1903, а также в Windows 11 и Windows Server 2022;
  • В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V (SVM Mode).

Как установить Windows Subsystem for Linux (WSL2)?

Компонент WSL по умолчанию отключен в Windows. Современных дистрибутивах Windows 10 и Windows 11 для установки среды WSL достаточно выполнить команду:

wsl --install

Этак команда автоматически включит все необходимые компоненты Windows, необходимые для работы WSL, установить обновление ядра Linux для WSL2, загрузит дистрибутив Ubuntu (по-умолчанию) и установит его в WSL.

команда для быстрой установки wsl в windows 10 и 11

Осталось перезагрузить компьютер, и вы можете запускать среду WSL!

Вы можете установить для WSL другой дистрибутив Linux. Выведите список доступных дистрибутивов:

wsl --list --online

Укажите имя дистрибутива Linux, который установить в WSL. Например:

wsl --install -d kali-linux

список доступных дистрибутивов Linux для WSL

Если в BIOS/UEFI компьютера не включена виртуализация, при установке WSL вы получите ошибку:

Installation failed with error 0x80070003 or error 0x80370102” it means that Bios Level Virtualization is not enabled on your computer.

Вы можете установить WSL2 в Windows вручную. Для этого придется вручную последовательно выполнить все этапы, который команда wsl —install запускала автоматически:

  1. Установить WSL
  2. Включить компонент виртуалзации VirtualMachinePlatform
  3. Установить ядро WSL 2
  4. Скачать и установить дистрибутив Linux для WSL

Сначала установите следующие компоненты Windows:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform

установить компонент wsl в windows вручную

Перезагрузите компьютер.

Скачаем и установим обновление ядра Linux для WSL2 (WSL2 Linux kernel update package for x64 machines — https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi). Можете скачать пакет вручную или с помощью PowerShell:

Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile "$($env:userprofile)\Downloads\wsl_update_x64.msi" -UseBasicParsing
Invoke-Item "$($env:userprofile)\Downloads\wsl_update_x64.msi"
rm "$($env:userprofile)\Downloads\wsl_update_x64.msi"

windows subsyste for linux update setup

Еще раз перезагрузите компьютер и назначьте версию WSL 2 в качестве среды по-умолчанию:

wsl --set-default-version 2

wsl2 назначить по умолчанию

WSL: Установка дистрибутива Linux в Windows

После того, как ядро WSL установлено в Windows, вы можете установить один или несколько дистрибутивов Linux на компьютер.

Можно установить пакет с дистрибутивом Linux через Microsoft Store. Доступны следующие дистрибутивы:

  • Ubuntu
  • Debian
  • Kali Linux
  • OpenSUSE
  • Oracle Linux
  • SUSE Linux Enterprise Server
  • Fedora

Найдите нужную версию дистрибутива в Store и установите ее, нажав кнопку Получить (Get).

скачать образ linux для wsl из microsoft store

Если у вас отключен Windows Store, вы хотите установить дистрибутив WSL в Core редакции Windows Server или вам нужно установить WSL на Изолированном от интернета компьютере (оффлайн), вы можете скачать дистрибутив Ubuntu с помощью PowerShell командлета Invoke-WebRequest:

Invoke-WebRequest https://aka.ms/wslubuntu2204 -OutFile ubuntu-2204.appx –UseBasicParsing

Установите пакет для WSL с помощью:

Add-AppxPackage .\ubuntu-2204.appx

После окончания установки появится окно, в котором вам будет предложено указать имя пользователя и пароль для вашего дистрибутива.

задать пароль для wsl

После установки вы можете в меню Пуск появится отдельная программа для запуска Linux.

Также вы можете запустить ваш Linux из отдельной вкладки Windows Terminal или с помощью команды
wsl
.

Команды для управления WSL в Windows

Рассмотрим основные команды для управления ядром и дистрибутивами Linux в WSL.

Проверить текущую версию ядра WSL:

wsl --version

версия wsl в windows

Обновить ядро WSL вручную:

wsl --update

Откатится к предыдущему ядру WSL:

wsl --update rollback

Вывести список установленных версий Linux:

wsl --list

Вывести дистрибутив Linux, который используется по-умолчанию:

wsl --status

Дистрибутив Linux по-умолчанию в WSL можно изменить:

wsl --setdefault Ubuntu

Запустить определенный дистрибутив в WSL:

wsl -d kali-linux

Завершить среду WSL:

wsl --shutdown

Можно войти в WSL Ubuntu под root и сбросить пароль:
ubuntu config --default-user root
Passwd

Вернуть пользователя по умолчанию
ubuntu config --default-user your_username

Для настройки параметров WSL и дистрибутивов Linux используются конфиг файлы:

  • wsl.conf – файл с настройками конкретного дистрибутива Linux (находится в директории /etc)
  • .wslconfig – глобальные настройки WSL, которые применяются ко всем дистрибутовам (находится в профиле пользователя в
    %UserProfile%
    )

Например, если вы хотите ограничить использование оперативной памяти и CPU компьютера дистрибутивами Linux в WSL, создайте такой файл
%UserProfile%\.wslconfig
:

[wsl2]
memory=2GB
processors=2

Использование Linux в среде WSL

Дистрибутив Linux, установленный в WSL является полноценной операционной системой. Поэтому после установки рекомендуется выполнить обновление пакетов. Для Ubuntu выполните команду:

$ sudo apt-get update && sudo apt-get upgrade -y

обновление пакетов в ubuntu wsl

Файловая система вашего дистрибутива Linux хранится в профиле пользователя в виде VHDX файла. Например, виртуальный диск Ubuntu хранится в папке
%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState

файл vhdx образа диска в linux wsl

Файловая система Linux в WSL монтируется в виде сетевой папки прямо в проводник Windows.

Также для прямого доступа к файлам WSL из Windows можно использовать UNC путь. Например:

notepad \\wsl$\Ubuntu\sysops\home\1122.txt

В свою очередь локальные диски Windows монтируются в WSL в папку mnt. Вывести список файлов папок на диске C:

wsl
ls /mnt
ls/mnt/c

просмот файлов на диске windows из wsl

Другие примеры запуска Linux команд из Windows:
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”

Вы можете установить любые пакеты в Linux. Например, установите файловый менеджер Midnight Commander:

$ sudo apt-get install mc

В современной версии WSL 2 вы можете запускать из Windows любые приложения Linux с графическим интерфейсом (X11 и Wayland). Например, установите графический редактор:

$ sudo apt install gimp -y

Чтобы запустить его из Windows просто выполните команду:

wsl gimp

Подсистема Windows для Linux (WSL) — это функция операционной системы Windows, которая позволяет запускать среду GNU / Linux внутри Windows — без затрат на традиционную виртуальную машину или настройку с двойной загрузкой. WSL требует меньше ресурсов (CPU, памяти и места на диске), чем полноценная виртуальная машина. WSL также позволяет запускать инструменты и приложения командной строки Linux наряду с приложениями командной строки Windows, а также получать доступ к файлам Windows из Linux. Это позволяет при желании использовать приложения Windows и инструменты командной строки Linux для одного и того же набора файлов. Поддерживается множество дистрибутивов, включая Ubuntu, Debian, Kali Linux, OpenSUSE и другие. Можно установить свой дистрибутив, импортировав образ в формате tar.gz.

Общие сведения

Установить WSL можно на Windows 10 версии 2004 (сборка 19041) и выше и Windows 11. Для работы с ним лучше всего использовать Windows Terminal.

WSL использует собственную файловую систему, отделённую от файловой системы Windows (так как в Linux дискам не присваиваются буквы, а предоставляются точки монтирования). Корень файловой системы — / — точка монтирования корневого раздела (или папки в случае с WSL). WSL использует файловую систему Windows как смонтированный диск, и доступ к какому-либо каталогу (к примеру, к диску C:\) в Windows из WSL можно получить по пути /mnt/c/.

Из Windows можно получить доступ к приложениям, запущенным в Linux. Например, доступ к сайту можно получить как обычно — localhost:port. Однако в некоторых случаях следует использовать IP-адрес для подключения (ip:port), который можно взять в файле /etc/resolv.conf — из-за того, что в WSL 2 используется собственный виртуальный адаптер Ethernet со своим уникальным IP-адресом.

Установка

Подсистема WSL поставляется вместе с ОС Windows, однако её необходимо предварительно включить. Можно использовать упрощенную команду, в таком случае подсистема включится и установить дистрибутив Ubuntu (он используется по умолчанию):

С параметром --no-distibution можно только включить WSL, не устанавливая дистрибутив:

1
wsl --install --no-distribution

После первой установки (или включения WSL) может потребоваться перезагрузка компьютера.

В целом установка дистрибутивов доступна несколькими способами:

  1. через Microsoft Store;
  2. через Windows Terminal командой wsl --install или аналогичной;
  3. через Windows Terminal, экспортировав необходимый дистрибутив.

Список доступных для установки из терминала дистрибутивов можно получить командой:

1
2
wsl --list --online
wsl -l -o

На 7 августа 2023 года список следующий:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NAME                                   FRIENDLY NAME
Ubuntu                                 Ubuntu
Debian                                 Debian GNU/Linux
kali-linux                             Kali Linux Rolling
Ubuntu-18.04                           Ubuntu 18.04 LTS
Ubuntu-20.04                           Ubuntu 20.04 LTS
Ubuntu-22.04                           Ubuntu 22.04 LTS
OracleLinux_7_9                        Oracle Linux 7.9
OracleLinux_8_7                        Oracle Linux 8.7
OracleLinux_9_1                        Oracle Linux 9.1
openSUSE-Leap-15.5                     openSUSE Leap 15.5
SUSE-Linux-Enterprise-Server-15-SP4    SUSE Linux Enterprise Server 15 SP4
SUSE-Linux-Enterprise-15-SP5           SUSE Linux Enterprise 15 SP5
openSUSE-Tumbleweed                    openSUSE Tumbleweed

Нужный из списка дистрибутив можно установить командой:

1
2
wsl --install -d <DistName>
wsl --install -d Debian

Установку можно дополнить ключом --no-launch, тогда WSL не будет запускать дистрибутив сразу после установки. При этом дистрибутив не будет отображаться среди установленных — выполнение команды означает только загрузку дистрибутива для последующего повторного выполнения wsl --install.

Каждый раз, когда устанавливается новый дистрибутив WSL Linux, для него в Windows Terminal создаётся новый профиль для подключения.

По умолчанию дистрибутивы создаются в каталоге C:\Users\username\AppData\Local\Packages.

После завершения процесса установки дистрибутива будет предложено создать нового пользователя и установить ему пароль. Этот пользователь относится к каждому устанавливаемому дистрибутиву и не имеет отношения к пользователю Windows. После создания пользователя, он станет пользователем по умолчанию (будет автоматически входить в систему при запуске) и учетная запись будет считаться администратором Linux (с правами выполнения sudo).

Изменение языка дистрибутива

При установке дистрибутива WSL пытается автоматически определить и применить локаль в соответствии с локализацией Windows. Если ей это сделать не удаётся, можно изменить язык принудительно (после выполнения перезагрузить дистрибутив):

1
sudo update-locale LANG=en_US.UTF8

Дополнительные команды WSL

Работа дистрибутивов

Запустить дистрибутив по умолчанию в домашнем каталоге пользователя можно следующей командой:

Для запуска другого дистрибутива (не по умолчанию) следует указать параметр --distribution:

1
wsl --distribution <DistName>

Можно запустить дистрибутив из-под другого пользователя:

1
wsl --user <Username> # или wsl -u <Username>

Дистрибутив по умолчанию указывается параметров --set-default-version:

1
wsl --set-default <DistName>

С параметром --set-version можно указать версию WSL (1 или 2), с которой требуется запустить тот или иной дистрибутив:

1
wsl --set-version <DistName> <VersionNumber>

Завершить работу одного конкретного или сразу всех дистрибутивов можно следующим образом:

1
2
wsl --terminate <DistName> # завершить работу <DistName>
wsl --shutdown # завершает работу всех запущенных дистрибутивов

Удаляется дистрибутив параметров -unregister:

1
wsl --unregister <DistName>

Параметры WSL

Обновить WSL можно следующей командой:

1
2
wsl --update # версия с Microsoft Store
wsl --update --web-download # версия с Github

Текущая конфигурация WSL выводится при передаче параметра --status или --version:

1
2
wsl --status
wsl --version

Установить версию WSL по умолчанию (1 или 2) можно параметром --set-default-version:

1
wsl --set-default-version <VersionNumber>

Монтировать дополнительные разделы в дистрибутивы можно параметром --mount. Он содержит следующие ключи:

  • --vhd — указывает, что монтируется виртуальный жесткий диск;
  • --name — монтируется диск с пользовательским именем;
  • --bare — подключает, но не монтирует диск;
  • --type <Filesystem> — тип файловой системы, используемый при монтировании (ext4 по умолчанию);
  • --partition <PartNumber> — порядковый номер раздела при монтировании.

Для монтирования разделов необходимы права администратора

1
wsl --mount C:\Users\Profile\Projects\FirstProject

Размонтировать один конкретный раздел или все можно командой --unmount:

1
2
wsl --unmount <DiskPath> # размонтировать <DiskPath>
wsl --unmount # размонтировать все диски и разделы

Список дистрибутивов

Команда --list показывает список дистрибутивов. Дополнительный ключ к команде может отфильтровать вывод:

  • --all — показывает все дистрибутивы;
  • --verbose — показывает установленные дистрибутивы;
  • --running — показывает только запущенные дистрибутивы;
  • --quiet — отображает только названия.

Работа с WSL

Изменение хостнейма

Для начала необходимо добавить нужное имя в файл /etc/wsl.conf в раздел network:

1
2
3
[network]
hostname = ubuntu_wsl
generateHosts = false

​ После этого следует поменять хостнейм в файле /etc/hostname:

1
2
ubuntu_wsl
/etc/hostname

Взаимодействие с Windows

Для максимальной производительности рекомендуется хранить файлы для работы в Linux в файловой системе WSL — в той же операционной системе, где они используются. Доступ к файлам возможен из разных ОС, но это значительно снижает производительность.

В дистрибутивах можно вызывать приложения WIndows и передавать в параметр файлы и каталоги Linux. Например, чтобы открыть текущий каталог в стандартном проводнике (Explorer), необходимо написать:

С файлами ситуация аналогичная:

В названии приложения обязательно нужно указывать разрешение (exe).

Это работает и в обратную сторону — утилиты Linux можно запускать напрямую из PowerShell. Например, чтобы отобразить содержимое какого-либо каталога Windows, можно ввести:

Можно смешивать команды Windows и Linux. Например, можно отобразить список файлов ls -la и отфильтровать результаты командой PowerShell findstr или наоборот — отобразить каталоги командой dir и отфильтровать командой grep

1
2
wsl ls -la | findstr "git"
dir | wsl grep git

Запуск графических приложений Linux

WSL 2 поддерживает запуск приложений с графическим интерфейсом (X11 и Wayland) в Windows с полностью интегрированным интерфейсом для ПК. Их можно запускать из меню “Пуск” Windows, закреплять на панели задач, переключаться между приложениями по Alt+Tab. Приложения поддерживают буфер обмена Windows.

Для запуска графических приложений необходим драйвер vGPU:

  • Драйвер графического процессора Intel
  • Драйвер графического процессора AMD
  • Драйвер графического процессора NVIDIA

Для запуска приложения из консоли достаточно написать только его название или название с файлом (например, для редактирования) на примере gedit:

Сетевые приложения

IP-адрес хост-машины и IP-адрес Linux-дистрибутива в WSL могут быть разными. IP-адрес хост-машины — это IP-адрес самого компьютера, а IP-адрес Linux-дистрибутива — это IP-адрес, который присваивается в виртуальной сети WSL. Обычно IP-адрес Linux-дистрибутива настраивается автоматически и не зависит от настроек хост-машины.

1
2
wsl hostname -i # IP-адрес дистрибутива
cat /etc/resolv.conf # IP-адрес компьютера с Windows

Управление дисковым пространством

WSL 2 использует платформу виртуализации для установки дистрибутивов Linux вместе с основной операционной системой Windows, создавая виртуальный жесткий диск (VHD) для хранения файлов для каждого из устанавливаемых дистрибутивов Linux. Эти жесткие диски используют тип файловой системы ext4 и представлены на жестком диске Windows в виде файла ext4.vhdx. WSL автоматически изменяет размер этих файлов VHD в соответствии с потребностями хранилища. По умолчанию каждому VHD-файлу, используемому WSL 2, изначально выделяется максимальный объем дискового пространства в 1 ТБ.

Проверить объем дискового пространства, доступного на VHD для дистрибутива Linux, установленного вместе с WSL 2, с помощью команды Linux df.

1
wsl.exe --system -d <distribution-name> df -h /mnt/wslg/distro

Выходные данные будут включать:

  • идентификатор файловой системы VHD;
  • общий размер диска;
  • используемый объем пространства;
  • доступный объём свободного места;
  • процент использования;
  • путь к каталогу, в который смонтирован диск.

Путь к файлу диска:

1
(Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss | Where-Object { $_.GetValue("DistributionName") -eq '<distribution-name>' }).GetValue("BasePath") + "\ext4.vhdx"

Конфигурации WSL и дистрибутивов

Файлы wsl.conf и .wslconfig используются для настройки дополнительных параметров для каждого дистрибутива (wsl.conf) или глобально для всех дистрибутивов WSL 2 (.wslconfig).

  • файл wsl.conf хранится в каталоге /etc в виде файла. Используется для настройки параметров каждого дистрибутива WSL 1 и WSL 2;
  • файл .wslconfig хранится в %UserProfile% каталоге. Используется для настройки всех дистрибутивов Linux, работающих под управлением WSL 2.

WSL обнаруживает существование этих файлов, читает их содержимое и автоматически применяет параметры при каждом запуске. Если файл отсутствует или содержит ошибку, то WSL продолжит запускаться в обычном режиме, но без применения параметров конфигурации.

wsl.conf

Файл wsl.conf настраивает параметры для каждого дистрибутива отдельно:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[boot] # доступна только на Windows 11 и Server 2022
systemd=true # включает поддержку systemd
command="" # строка команд, которые должны запускаться при запуске экземпляра WSL. Команда запускается от имени root
# command=service docker start

[automount]
enabled=true # автоматически монтировать диски Windows (C:\ и другие) с помощью DrvFs в /mnt/
mountFsTab=true # автоматически обрабатывает /etc/fstab при запуске дистрибутива
root=/mnt/ # устанавливает каталог, куда будут монтироваться диски Windows
options="" # параметры автоматического монтирования
# options = "metadata,uid=1003,gid=1003,umask=077,fmask=11,case=off"

[network]
generateHosts=true # WSL сам генерирует файл /etc/hosts
generateResolvConf=true # WSL сам генерирует файл /etc/resolv.conf
hostname="Hostname" # устанавливает имя Unix-компьютера. По умолчанию - имя компьютера Windows

[interop]
enabled=true # установка этого ключа в true означает поддержку запуска Windows-процессов
appendWindowsPath=true # установка этого ключа определяет, будет ли WSL добавлять элементы пути Windows в переменную окружения $PATH

[user]
default=Username # пользователь по умолчанию

.wslconfig

Файл .wslconfig настраивает параметры глобально для всех дистрибутивов Linux, работающих с WSL 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[wsl2]
kernel=path # абсолютный путь Windows к пользовательскому ядру Linux
memory=4GB # объём выделяемой памяти для WSL (по умолчанию 50% или 8 Гбайт - меньшее из них)
processors=10 # сколько логических процессов назначить WSL. По умолчанию - столько же, сколько и Windows
localhostForwarding=true # логическое значение, указывающее, должны ли порты, привязанные к wildcard или localhost в виртуальной машине, подключаться с хоста через localhost:port
kernelCommandLine=blank # дополнительные аргументы командной строки ядра
safeMode=false # запускает экземпляр WSL в безопасном режиме
swap=25% # сколько виртуальной памяти добавить к дистрибутиву
swapFile=path # абсолютный  путь к файлу swal
pageReporting=true # позволяет Windows освобождать неиспользуемую в WSL память
guiApplications=true # включение поддержки графических приложений (только в Windows 11)
debugConsole=false # логическое значение для включения окна консоли вывода, отображающего содержимое dmesg при запуске экземпляра дистрибутива WSL (только в Windows 11)
nestedVirtualization=true # включение вложенной виртуализации (только в Windows 11)
vmIdleTimeout=60000 # количество миллисекунд, в течение которых виртуальная машина простаивает, прежде чем она будет выключена (только в Windows 11)

Резервное копирование и перемещение

Лучший способ создать резервную копию или переместить дистрибутивы (в рамках одного ПК или на другой) — использовать команды экспорта и импорта, доступные в Windows с версии 1809. Можно экспортировать весь дистрибутив в архив с помощью команды wsl --export. Затем его импортировать обратно в WSL с помощью команды wsl --import, которая может указать новое расположение для импорта, что также сохранять состояния дистрибутива.

Экспорт дистрибутива требует много места на жестком диске. Если места недостаточно, то можно использовать методы Linux для перемещения всех файлов:

  1. архивировать домашний и другие необходимые каталоги командой tar -czf <archiveName> <directory>. После переноса на новый дистрибутив архив следует разархивировать командой tar -xzf <archiveName>;
  2. можно экспортировать список установленных пакетов через apt: dpkg --get-selections | grep -v deinstall | awl '{print $1}' > packages.txt, а затем установить все приложения на новом дистрибутиве командой sudo apt install -y $(cat packages.txt).

При экспорте можно указать ключ --vhd, указывающий, что дистрибутив следует экспортировать в виде файла VHDX.

Команду импорта можно дополнить ключами --version <Version — указывающий версию WSL (1 или 2) и --vhd — указывающий, что представленный файл является файлом VHDX, а не файлом tar.gz.

Файл tar можно получить разными способами, например:

  • загрузить с сайта разработчика (при наличии);
  • экспортировать контейнер дистрибутива.

Далее файл tar нужно импортировать в WSL:

1
2
3
4
5
6
7
# экспорт
wsl --export <DistName> <Filename>
wsl --export Debian C:\WSLDistros\export.tar.gz

# импорт
wsl --import <DistName> <InstallLocation> <FileName>
wsl --import Debian C:\Users\username\WSL\ C:\Users\username\export.tar.gz

In this tutorial, we explain maybe the simplest possible method for installing a Linux Desktop and Linux Graphics User Interface (GUI) in Windows Subsystem for Linux (WSL2). Here is a brief overview of the tasks that we will perform in this tutorial in order to install the desktop environment:

1. Install WSL2 and a desired Linux distribution. In our case, we will install Ubuntu 24.04

2. Install Tasksel: https://wiki.debian.org/tasksel
Tasksel is a software package that can be used to install the Linux Desktop Environment (Linux GUI)

3. Install xrdp. Xrdp is a software package that enables us to setup and use a remote desktop protocol. Xrdp is developed by Microsoft and it allows us to remotely access and interact with a server’s  graphics user interface. Xrdp is an abbreviation (acronym) for X Remote Desktop Protocol.

4. Use the Windows remote desktop connection to connect to the Linux Desktop Environment.

The YouTube tutorial is given below.

1. Install WSL2

If you do not have WSL2 installed on your system, you can install it as follows. Click on Start and search for Windows PowerShell. Open power shell in the administrator mode by doing a right click and by clicking on “run as administrator”. Check if WSL is already installed. You can do that by typing

wsl -l -v

If you see an output this means that WSL is installed. If not, to install WSL, you need to type

wsl --install

Then, after restarting the system, you will be able to use WSL. Note that with WSL there will be a default Linux Ubuntu version installed. We can change the default distribution and install any other supported distribution. We will install Ubuntu 24.04.

After you restart the system, open again Windows PowerShell in the administrator node. Type this

wsl -l -v

and you will see the list of installed distributions.

To list all available Linux distributions that can be run through WSL, type:

wsl --list  --online

We will install Ubuntu 24.04. To do that, type this:

wsl --install -d Ubuntu-24.04

Type exist to exit the installed linux distribution. We will manually start the installed distribution later on.

To list all installed distributions, type this

wsl -l -v

To start Ubuntu 24.04. Click on start and search for Ubuntu 24.04. By clicking on Ubuntu 24.04, Ubuntu session will start.

Another way to start Ubuntu is to go back to the power shell and to type

wsl -d Ubuntu-24.04

Let us use a graphical approach to start Ubuntu. Click on Start and search for Ubuntu 24.04, and start Ubuntu 24.04.

Then, update

sudo apt update
sudo apt upgrade

Install Tasksel, Select the Linux GUI Distribution, and Install Xrdp

To install and run tasksel, type this

sudo apt install tasksel
sudo tasksel

After starting tasksel, you will see this menu

Here, we will select GNOME, to do that use the keyboard arrows to navigate and press space to select, then, press TAB to move to OK and press enter.

After that, the installation process will start.

To install xrdp, type this

sudo apt install xrdp -y 

Confirm the installation with

sudo systemctl status xrdp

The status should be active (running). To exit this window, type this CTRL+C

If this program is not running, start it with

sudo systemctl start xrdp

Check the address of the Ubuntu Session and Start Remote Desktop Connection

To check the address, type this

ip a 

and copy the inet address. In our case, the inet address is 172.29.173.75

Then, start a Windows Remote Desktop Connection, by clicking on Start and searching for Remote Desktop Connection

Start the Remote Desktop Connection, and type the inet address in the Computer field.

Then connect.

Then, you will see this screen

and enter the username and password you used to start the Ubuntu 24.04. After you enter the username and password, the Ubuntu GNOME section will start

Welcome to WSLg

WSLg is short for Windows Subsystem for Linux GUI and the purpose of the project is to enable support for running Linux GUI applications (X11 and Wayland) on Windows in a fully integrated desktop experience.

WSLg provides an integrated experience for developers, scientists or enthusiasts that prefer or need to run Windows on their PC but also need the ability to run tools or applications which work best, or exclusively, in a Linux environment. While users can accomplish this today using a multiple system setup, with individual PC dedicated to Windows and Linux, virtual machine hosting either Windows or Linux, or an XServer running on Windows and projected into WSL, WSLg provides a more integrated, user friendly and productive alternative.

WSLg strives to make Linux GUI applications feel native and natural to use on Windows. From integration into the Start Menu for launch to appearing in the task bar, alt-tab experience to enabling cut/paste across Windows and Linux applications, WSLg enables a seamless desktop experience and workflow leveraging Windows and Linux applications.

WSLg Integrated Desktop

Installing WSLg

Pre-requisites

  • WSLg is supported on both Windows 11 and Windows 10. Windows 10 users must ensure their Windows 10 installation is fully up to date by visiting Windows Update and installing all available updates.

  • WSLg is available both as part of the Windows 11 WSL inbox support as well as through the Windows Subsystem for Linux from the Microsoft Store. It is highly recommended to use the Microsoft Store version of WSL, which supports both Windows 10 and Windows 11, and contains the most up to date version of WSL and WSLg.

  • Make sure to update your graphics driver to the latest driver available from your GPU manufacturer’s website to benefit from GPU acceleration in your WSL environment.

Install instructions (Fresh Install — no prior WSL installation)

From a command prompt with administrator privileges, run the command wsl --install -d Ubuntu, then reboot if prompted.

After reboot the installation will continue. You’ll be asked to enter a username and password. These will be your Linux credentials, they can be anything you want and don’t have to match your Windows credentials.

Voilà! WSL and WSLg are installed and ready to be used!

Install instructions (Existing WSL install)

If you have an existing WSL installation without WSLg and want to update to the latest version of WSL which includes WSLg, run the command wsl --update from an elevated command prompt.

Please note that WSLg is only compatible with WSL 2 and will not work for WSL distribution configured to work in WSL 1 mode. Verify that your Linux distro is configured for running in WSL 2 mode, if not switch to WSL 2. While you can continue to run Linux distro in WSL 1 mode after installing WSLg if you so desired, a distro configured to run in WSL 1 mode will not be able to communicate with WSLg and will not be able to run GUI applications.

You can list your currently installed distro and the version of WSL they are configured for using the following command from an elevated command prompt.

If running in version 1 mode, switch to version 2. This can take a while.

   wsl --set-version _distro_name_ 2

Restart WSL by running this command from an elevated command prompt, make sure to save any pending work first:

Updating WSL + WSLg

To update to the latest version of WSL and WSLg released for preview, simply run wsl --update from an elevated command prompt or powershell.

You’ll need to restart WSL for the changes to take effect. You can restart WSL by running wsl --shutdown from an elevated command prompt. If WSL was currently running, it will shutdown, make sure to first save any in progress work! WSL will be automatically restarted the next time you launch a WSL application or terminal.

First Launch

If you have installed the Ubuntu Linux distro per these instructions, you’ll find an Ubuntu icon in your start menu, launch it. This will launch the WSL 2 VM, launch the Ubuntu WSL distro in that VM and give you a terminal to interact with it. Voilà! You’re running Linux on Windows!

If you would like to explore additional Linux distributions built for WSL, you can use the wsl --list --online command from an elevated command prompt to enumerate the list of available distributions for your system. You can have multiple Linux distributions installed within WSL and they will happily coexist side-by-side, so don’t be scared to experiment and try things out.

Congrats you are done and ready to use GUI apps!

Install and run GUI apps

If you want to get started with some GUI apps, you can run the following commands from your Linux terminal to download and install some popular applications. If you are using a different distribution than Ubuntu, it may be using a different package manager.

## Update list of available packages
sudo apt update

## Gedit
sudo apt install gedit -y

## GIMP
sudo apt install gimp -y

## Nautilus
sudo apt install nautilus -y

## VLC
sudo apt install vlc -y

## X11 apps
sudo apt install x11-apps -y

## Google Chrome
cd /tmp
sudo wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb 
sudo apt install --fix-broken -y
sudo dpkg -i google-chrome-stable_current_amd64.deb

## Microsoft Teams
cd /tmp
sudo curl -L -o "./teams.deb" "https://teams.microsoft.com/downloads/desktopurl?env=production&plat=linux&arch=x64&download=true&linuxArchiveType=deb"
sudo apt install ./teams.deb -y

## Microsoft Edge Dev Browser
sudo curl https://packages.microsoft.com/repos/edge/pool/main/m/microsoft-edge-dev/microsoft-edge-dev_118.0.2060.1-1_amd64.deb -o /tmp/edge.deb
sudo apt install /tmp/edge.deb -y

Once these applications are installed, you’ll find them in your start menu under the distro name. For example Ubuntu -> Microsoft Edge. You can also launch these from your terminal window using the commands:

  • xcalc, xclock, xeyes
  • gimp
  • gedit ~/.bashrc
  • nautilus
  • vlc
  • google-chrome
  • teams
  • microsoft-edge

WSLg Architecture Overview

WSLg Architecture Overview

User Distro

The user distro is essentially the WSL distribution you are using for your Linux work. You can use the command wsl --list --online from an elevated Windows command prompt to list the WSL distributions available on your system. You can run multiple user distros side-by-side and they will peacefully coexist, so don’t be afraid of trying out new distro. Each user distro will be paired with a unique instance of the system distro, but you can still interact across GUI applications running in different user distro seamlessly, such as cut/paste between them. The underlying containerization of the various userspace should be invisible to you.

All user and system distros for a particular Windows user run within the same WSL virtual machine against a single instance of the Linux kernel. Different Windows users on a PC have their own VM and instance of WSL. Your Linux environment is guaranteed to always be your own and not shared with other Windows users on the same PC.

WSLg System Distro

The system distro is where all of the magic happens. The system distro is a containerized Linux environment where the WSLg XServer, Wayland server and Pulse Audio server are running. Communication socket for each of these servers are projected into the user distro so client applications can connect to them. We preconfigure the user distro environment variables DISPLAY, WAYLAND_DISPLAY and PULSE_SERVER to refer these servers by default so WSLg lights up out of the box.

Users wanting to use different servers than the one provided by WSLg can change these environment variables. User can also choose to turn off the system distro entirely by adding the following entry in their .wslconfig file (located at c:\users\MyUser\.wslconfig). This will turn off support for GUI applications in WSL.

[wsl2]
guiApplications=false

The system distro is based on the Microsoft CBL-Mariner Linux. This is a minimal Linux environment, just enough to run the various pieces of WSLg. For details on how to build and deploy a private system distro please see our build instructions.

Every WSL 2 user distro is paired with its own instance of the system distro. The system distro runs partially isolated from the user distro to which it is paired, in its own NS/PID/UTS namespace but shares other namespaces such as IPC, to allow for shared memory optimization across the boundary.

While a user can get a terminal into the system distro, the system distro is not meant to be used directly by users. Every instance of the system distro is loaded read-only from its backing VHD. Any modifications, made to the in-memory instance of the system distro (such as installing new packages or creating a new file), are effectively discarded when WSL is restarted. The reason we do this is to enable a servicing model for the system distro where we replace the old one with the new one without having to worry about migrating any user data contained within. We use a read-only mapping such that the user gets a well known discard behavior on any changes, every time WSL is restarted, instead of getting a surprise when WSL is serviced.

Although the Microsoft published WSLg system distro as read-only, we do want to encourage folks to tinker with it and experiment. Although we expect very few folks to actually need or want to do that, we’ve shared detailed instruction on our contributing page on how to both build and deploy a private version of the system distro. Most users who just want to use GUI applications in WSL don’t need to worry about those details.

WSLGd

WSLGd is the first process to launch after init. WSLGd launches Weston (with XWayland), PulseAudio and establishes the RDP connection by launching mstsc.exe on the host in silent mode. The RDP connection will remain active and ready to show a new GUI applications being launch on a moment’s notice, without any connection establishment delays. WSLGd then monitors these processes and if they exit by error (say as a result of a crash), it automatically restarts them.

Weston

Weston is the Wayland project reference compositor and the heart of WSLg. For WSLg, we’ve extended the existing RDP backend of libweston to teach it how to remote applications rather than monitor/desktop. We’ve also added various functionality to it, such as support for multi-monitor, cut/paste, audio in/out, etc…

The application integration is achieved through an RDP technology called RAIL (Remote Application Integrated Locally) and VAIL (Virtualized Application Integrated Locally). The main difference between RAIL and VAIL is how pixels are transported across from the RDP server to the RDP client. In RAIL, it is assumed that the Server and Client are running on different physical systems communicating over the network and thus pixels need to be copied over the RDP transport. In VAIL, it is understood that the Server and Client are on the same physical system and can share memory across the Guest/Host VM boundary. We’ve added support for both RAIL and VAIL to the libweston RDP backend, although for WSLg only the VAIL support is effectively used. While building WSLg, we first implemented RAIL while the necessary pieces enabling the switch to VAIL were being developed in parallel. We decided to keep that support in as it could reuse in other interesting scenarios outside of WSLg, for example for remoting application from a Pi running Linux. To share memory between the Linux guest and Windows host we use virtio-fs.

RAIL-Shell

Weston is modular and has various shells today, such as the desktop shell, fullscreen shell (aka kiosk), and automative shell. For WSLg we introduced a new shell called the RAIL Shell. The purpose of the RAIL Shell is to help with the remoting of individual windows from Linux to Windows, as such the shell is very simplistic and doesn’t involve any actual widgets or shell owned pixels.

FreeRDP

Weston leverages FreeRDP to implement its backend RDP Server. FreeRDP is used to encode all communications going from the RDP Server (in Weston) to the RDP Client (mstsc on Windows) according to the RDP protocol specifications. It is also used to decode all traffic coming from the RDP Client into the RDP server.

Pulse Audio Plugin

For audio in (microphone) and out (speakers/headphone) WSLg runs a PulseAudio server. WSLg uses a sink plugin for audio out, and a source plugin for audio in. These plugins effectively transfer audio samples between the PulseServer and the Weston RDP Server. The audio streams are merged by the Weston RDP Server onto the RDP transport, effectively enabling audio in/out in the Weston RDP backend across all scenarios (Desktop/RAIL/VAIL style remoting), including WSLg.

WSL Dynamic Virtual Channel Plugin (WSLDVCPlugin)

WSLg makes use of a custom RDP virtual channel between the Weston RDP Server and the mstsc RDP Client running on the Windows host. This channel is used by Weston to enumerate all Linux GUI applications (i.e. applications which have a desktop file entry of type gui) along with their launch command line and icon. The open source WSLDVCPlugin processes the list of Linux GUI applications sent over this channel and creates links for them in the Windows start menu.

OpenGL accelerated rendering in WSLg

While WSLg works with or without virtual GPU support, if you intend to run graphics intensive applications such as Blender or Gazebo, it is best to be running on a system with a GPU and driver that can support WSL. An overview of our vGPU architecture and how we make it possible for Linux applications to access the GPU in WSL is available at our DirectX blog.

Support for OpenGL accelerated rendering is made possible through the work our D3D team has done with Collabora and the Mesa community on creating a d3d12 Gallium driver.

Support for Linux, including support for WSLg, has been upstream and part of the Mesa 21.0 release. To take advantage of this acceleration, you’ll need to update the version of Mesa installed in your user distro. It also requires that your distro vendor chose to build and publish the new d3d12 Gallium driver to their package repository. We’re working with the various WSL distro publishers to inform them of these changes.

Please note that for the first release of WSLg, vGPU interops with the Weston compositor through system memory. If running on a discrete GPU, this effectively means that the rendered data is copied from VRAM to system memory before being presented to the compositor within WSLg, and uploaded onto the GPU again on the Windows side. As a result, there is a performance penalty proportionate to the presentation rate. At very high frame rates such as 600fps on a discrete GPU, that overhead can be as high as 50%. At lower frame rate or on integrated GPU, performance much closer to native can be achieved depending on the workload. Using a vGPU still provides a very significant performance and experience improvement over using a software renderer despite this v1 limitation.

WSLg Code Flow

WSLg builds on the great work of the Linux community and makes use of a large number of open source projects. Most components are used as-is from their upstream version and didn’t require any changes to light up in WSLg. Some components at the heart of WSLg, in particular Weston, FreeRDP and PulseAudio, required changes to enable the rich WSLg integration. These changes aren’t yet upstream. Microsoft is working with the community to share these contributions back with each project such that, over time, WSLg can be built from upstream component directly, without the need for any WSLg specific modifications.

All of these in-flight contributions are kept in Microsoft mirror repos. We keep these mirrors up to date with upstream releases and stage our WSLg changes in those repos. WSLg pulls and builds code from these mirror repos as part of our Insider WSLg Preview releases. These mirrors are public and accessible to everyone. Curious developers can take a peek at early stages of our contribution by looking at code in those mirrors, keeping in mind that the final version of the code will likely look different once the contribution reaches the upstream project and is adapted based on the feedback receives by the various project owners. All of our mirrors follow the same model. There is a main branch which correspond to the upstream branch at our last synchronization point. We update the main branch from time to time to pick update from the upstream project. There is also a working branch that contains all of our in-flight changes. WSLg is built using the working branch from each of the mirror projects.

The projects that WSLg maintains mirrors for will change over time as in-flight contributions evolve. Once some contributions are upstream, it may no longer be necessary to maintain a mirror, at which point it will be removed and WSLg will start to leverage the upstream version of the component directly. As we light up new functionality in WSLg, new mirrors may be introduced to stage contributions to new components. As such, expect the list of mirrors to change overtime.

At this point in time, we have the following project mirrors for currently in-flight contributions.

Project Upstream Repo WSLg Mirror
Weston https://github.com/wayland-project/weston https://github.com/microsoft/Weston-mirror
FreeRDP https://github.com/FreeRDP/FreeRDP https://github.com/microsoft/FreeRDP-mirror
PulseAudio https://github.com/pulseaudio/pulseaudio https://github.com/microsoft/PulseAudio-mirror

The following is a high level overview of the currently in-flight contributions to each project contained within these mirrors.

Weston

WSLg leverages Weston as the Wayland compositor bridging the Linux and Windows worlds using RDP technology to remote application content between them. Weston already had an RDP backend, but it was limited to single-monitor-desktop remoting. We’ve greatly enhanced that RDP backend to include advanced functionality, such as multi-monitor support, clipboard integration for copy/paste, and audio in/out. We’ve enabled new remoting modes called RAIL (Remote Application Integrated Locally) and VAIL (Virtualized Application Integrated Locally), where individual applications, rather than desktops/monitors, are remoted. These changes are not specific to WSLg; they add functionality to the existing RDP backend and are reusable in other scenarios as well (i.e. using the new Weston RDP backend to remote application running on a Raspberry Pi to another device running an RDP client).

To enable rich integration in WSLg, we’ve also added a small plugin to the RDP backend specific to WSLg. In Weston, the plugin is responsible for attaching to the user distro and searching for installed applications (aka the desktop file). The plugin sends the Windows host a list of all applications found along with their launch commands and icons. On the Windows host, an open source mstsc plugin part of the WSLg project uses that information to create shortcuts for these Linux applications to the Windows Start Menu.

We’ve also fixed several bugs impacting various applications. Generally, these were problems that impacted Weston in all modes and were not specific to WSLg.

FreeRDP

Weston currently uses FreeRDP for its RDP Backend. WSLg continues to leverage FreeRDP and we have added support for a new RDP Protocol/Channel to enable VAIL optimized scenario as well as support for the WSLg plugin. We’ve also fixed various bugs that were impacting interops with mstsc or causing instability.

PulseAudio

For PulseAudio, our contributions focused on a sink and a source plugin that shuffle audio data between PulseAudio and the Weston RDP backend such that the audio data can be integrated over the RDP connection back to the host. There are no changes to the core of PulseAudio outside of adding these new plugins.

Contributing

If you would like to tinker with or contribute to WSLg, please see our CONTRIBUTING page for details, including how to build and run private a version of WSLg.

Reporting a non-security issues

For non-security related issues, such as reporting a bug or making a suggestion for a new feature, please use this project’s issues tracker.

Reporting security issues

To report security issues with WSLg or any other Microsoft products, please follow the instructions detailed here.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как задать режим лицензирования удаленных рабочих столов на windows server 2016
  • Wake on line windows 10
  • Проверить валидацию ключа windows
  • Номер соглашения enterprise agreement windows server 2016
  • Wic windows xp download