Windows subsystem for linux preview

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 works 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.

Windows Subsystem for Linux (WSL) — очень полезная возможность, которую Microsoft добавила в Windows 10 в 2017 году. Она позволяет разработчикам запускать среды GNU/Linux непосредственно в Windows, не требуя виртуальных машин (VM) или конфигураций с двойной загрузкой. Конечно, эта функция присутствует и в Windows 11. Ранее для включения WSL использовалось диалоговое окно «Включение или отключение компонентов Windows», но теперь Microsoft выпустила специальное приложение для WSL через Microsoft Store в Windows 11.

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

Microsoft отметила, что она уже добавила некоторые новые возможности в предварительную версию WSL в Microsoft Store. Это:

• WSLg теперь входит в состав приложения WSL!;
• Новые функции wsl.exe —mount!;
• Добавляйте —mount —vhd, чтобы упростить монтирование файлов VHD;
• Реализуйте обнаружение файловой системы для wsl —mount. Это изменение реализует определение типа файловой системы, если при использовании wsl.exe —mount не указан —type;
• Добавляйте функцию —name в wsl —mount. Это изменение добавляет поддержку для необязательного наименования точки монтирования при монтировании диска через WSL;
• Ядро Linux обновлено до версии 5.10.60.1;
• Добавлена вспомогательная функция индикатора выполнения, используемая для отображения сообщения «Пожалуйста, подождите» с анимированными точками в процессе преобразования, чтобы показать пользователям, что WSL все еще работает;
• Переключено wsl —install, чтобы не требовать аргумент —distribution. Это изменение переключает wsl —install, чтобы не требовать аргумент —distribution, но поддерживает поддержку, чтобы избежать нарушения существующих сценариев.
• Добавлена команда wsl.exe —version, которая отображает соответствующую информацию о версии;

Важно отметить, что версия WSL для Windows и аналог WSL для Microsoft Store могут сосуществовать и будут иметь доступ к одним и тем же дистрибутивам. Однако вариант из Microsoft Store будет иметь приоритет. Можно использовать дистрибутивы WSL 1, но в качестве предварительного условия вам необходимо убедиться, что WSL также включена в Windows, поскольку связанный драйвер еще не отделен от ОС.

Интересно, что Microsoft отметила, что будет продвигать версию WSL для Microsoft Store как оптимальный способ задействовать эту возможность на вашем компьютере с Windows 11, поскольку это обеспечит более быструю частоту обновления. Однако те, кто использует версию для Windows, по-прежнему поддерживаются. Компания будет использовать отзывы, чтобы определить целесообразность включения WSL в образ Windows.

Вы можете загрузить

Windows Subsystem for Linux Preview из Microsoft Store для Windows 11 здесь

.

From Wikipedia, the free encyclopedia

Windows Subsystem for Linux

Bash running on Windows 10

Other names WSL
Developer(s) Microsoft
Initial release August 2, 2016; 7 years ago
Stable release

WSL 2 1.2.5
/ April 20, 2023; 5 months ago[1]

Preview release

WSL 2 2.0.1
/ September 25, 2023; 12 days ago[2]

Repository github.com/Microsoft/WSL (issues only)
Operating system Windows 10, Windows 10 LTSB/LTSC, Windows Server 2016, Windows Server 2019, Windows 11, Windows Server 2022
Predecessor Windows Services for UNIX
Type Compatibility layer, Virtualization
License Subsystem: Proprietary commercial software;
Linux kernel: GNU GPLv2 (only) with some code under compatible GPL variants or under permissive licenses like BSD, MIT
Website learn.microsoft.com/windows/wsl/about

Windows Subsystem for Linux (WSL) is a feature of Windows that allows developers to run a Linux environment without the need for a separate virtual machine or dual booting. There are two versions of WSL: WSL 1 and WSL 2. WSL 1 was first released on August 2, 2016, and acts as a compatibility layer for running Linux binary executables (in ELF format) by implementing Linux system calls on the Windows kernel.[3] It is available on Windows 10, Windows 10 LTSB/LTSC, Windows 11,[4] Windows Server 2016, Windows Server 2019 and Windows Server 2022.

In May 2019, WSL 2 was announced,[5] introducing important changes such as a real Linux kernel,[6] through a subset of Hyper-V features. WSL 2 differs from WSL 1 in that WSL 2 runs inside a managed virtual machine that implements the full Linux kernel. As a result, WSL 2 is compatible with more Linux binaries than WSL 1, as not all syscalls were implemented in WSL 1. Since June 2019, WSL 2 is available to Windows 10 customers through the Windows Insider program, including the Home edition.[7] WSL is not available to all Windows 10 users by default. It can be installed either by joining the Windows Insider program or manual install.[8]

History[edit]

Microsoft’s first foray into achieving Unix-like compatibility on Windows began with the Microsoft POSIX Subsystem, superseded by Windows Services for UNIX via MKS/Interix, which was eventually deprecated with the release of Windows 8.1. The technology behind Windows Subsystem for Linux originated in the unreleased Project Astoria, which enabled some Android applications to run on Windows 10 Mobile.[9] It was first made available in Windows 10 Insider Preview build 14316.[10]

Whereas Microsoft’s previous projects and the third-party Cygwin had focused on creating their own unique Unix-like environments based on the POSIX standard, WSL aims for native Linux compatibility. Instead of wrapping non-native functionality into Win32 system calls as Cygwin did, WSL’s initial design (WSL 1) leveraged the NT kernel executive to serve Linux programs as special, isolated minimal processes (known as «pico processes») attached to kernel mode «pico providers» as dedicated system call and exception handlers distinct from that of a vanilla NT process, opting to reutilize existing NT implementations wherever possible.[11]

WSL beta was introduced in Windows 10 version 1607 (Anniversary Update) on August 2, 2016. Only Ubuntu (with Bash as the default shell) was supported. WSL beta was also called «Bash on Ubuntu on Windows» or «Bash on Windows». WSL was no longer beta in Windows 10 version 1709 (Fall Creators Update), released on October 17, 2017. Multiple Linux distributions could be installed and were available for install in the Windows Store.[12]

In 2017 Richard Stallman expressed fears that integrating Linux functionality into Windows will only hinder the development of free software, calling efforts like WSL «a step backward in the campaign for freedom.»[13]

Though WSL (via this initial design) was much faster and arguably much more popular than the previous UNIX-on-Windows projects, Windows kernel engineers found difficulty in trying to increase WSL’s performance and syscall compatibility by trying to reshape the existing NT kernel to recognize and operate correctly on Linux’s API. At a Microsoft Ignite conference in 2018, Microsoft engineers gave a high-level overview of a new «lightweight» Hyper-V VM technology for containerization where a virtualized kernel could make direct use of NT primitives on the host.[14] In 2019, Microsoft announced a completely redesigned WSL architecture (WSL 2) using this lightweight VM technology hosting actual (customized) Linux kernel images, claiming full syscall compatibility.[6] Microsoft announced WSL 2 on May 6, 2019,[5] and it was shipped with Windows 10 version 2004.[15] It was also backported to Windows 10 version 1903 and 1909.[16]

GPU support for WSL 2 to do GPU-accelerated machine learning was introduced in Windows build 20150.[17] GUI support for WSL 2 to run Linux applications with graphical user interfaces (GUIs) was introduced in Windows build 21364.[18] Both of them are shipped in Windows 11.

In April 2021, Microsoft released a Windows 10 test build that also includes the ability to run Linux graphical user interface (GUI) apps using WSL 2 and CBL-Mariner.[19][18] The Windows Subsystem for Linux GUI (WSLg) was officially released at the Microsoft Build 2021 conference. It is included in Windows 10 Insider build 21364 or later.[20]

Microsoft introduced a Windows Store version of WSL on October 11, 2021, for Windows 11.[21] It reached version 1.0.0 on November 16, 2022 with added support for Windows 10.

Notable releases[edit]

WSL as a Windows component

Release / Feature Preview build Public build
WSL (Beta) (Bash on Ubuntu on Windows) Windows 10 build 14316 Windows 10 version 1607 (Anniversary Update)
WSL (no longer Beta) Windows 10 build 16251 Windows 10 version 1709 (Fall Creators Update)
WSL 2 (lightweight VM) Windows 10 build 18917 Windows 10 version 2004 (also backported to 1903 and 1909)
WSL 2 GPU support Windows 10 build 20150 Windows 11 (also Windows 10 21H2)
WSL 2 GUI support (WSLg) (last version) Windows 10 build 21364 Windows 11
WSL as a Windows Store app

Version Comment
0.47.1 First version
0.67.6 systemd support
1.0.0 Generally available; Windows 10 support

Features[edit]

Bash running on Windows 10

WSL is available in Windows Server 2019 and in versions of Windows 10 from version 1607, though only in 64-bit versions.

Microsoft envisages WSL as «primarily a tool for developers – especially web developers and those who work on or with open source projects».[22] In September 2018, Microsoft said that «WSL requires fewer resources (CPU, memory, and storage) than a full virtual machine» (which prior to WSL was the most direct way to run Linux software in a Windows environment), while also allowing users to use Windows apps and Linux tools on the same set of files.[22]

The first release of WSL provides a Linux-compatible kernel interface developed by Microsoft, containing no Linux kernel code, which can then run the user space of a Linux distribution on top of it, such as Ubuntu,[23][24][25][26] openSUSE,[27] SUSE Linux Enterprise Server,[28][29][12] Debian[30] and Kali Linux.[31] Such a user space might contain a GNU Bash shell and command language, with native GNU command-line tools (sed, awk, etc.), programming-language interpreters (Ruby, Python, etc.), and even graphical applications (using an X11 server at the host side).[22]

The architecture was redesigned in WSL 2,[5] with a Linux kernel running in a lightweight virtual machine environment.

wsl.exe[edit]

The wsl.exe command is used to manage distributions in the Windows Subsystem for Linux on the command-line. It can list available distributions, set a default distribution, and uninstall distributions.[32] The command can also be used to run Linux binaries from the Windows Command Prompt or Windows PowerShell.[33] wsl.exe replaces lxrun.exe which is deprecated as of Windows 10 1803 and later.[34]

WSLg[edit]

Windows Subsystem for Linux GUI (WSLg) is built with the purpose of enabling support for running Linux GUI applications (X11 and Wayland) on Windows in a fully integrated desktop experience.[35] WSLg was officially released at the Microsoft Build 2021 conference and is included in Windows 10 Insider build 21364 or later.[20] However, with the introduction of Windows 11, WSLg is finally shipping with a production build of Windows, bringing support for both graphics and audio in WSL apps.[36]
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.[37]

Prerequisites for running WSLg include:

  • Windows 11 or Windows 10 Insider Preview builds 21362-21390.[35][38]
  • A system with virtual GPU (vGPU) enabled for WSL is recommended, as it will allow you to benefit from hardware accelerated OpenGL rendering.[35]

Design[edit]

WSL 1[edit]

Firefox for Linux running on WSL

LXSS Manager Service is the service in charge of interacting with the subsystem (through the drivers lxss.sys and lxcore.sys), and the way that Bash.exe (not to be confused with the Shells provided by the Linux distributions) launches the Linux processes, as well as handling the Linux system calls and the binary locks during their execution.[39] All Linux processes invoked by a particular user go into a «Linux Instance» (usually, the first invoked process is init). Once all the applications are closed, the instance is closed.

WSL 1’s design featured no hardware emulation / virtualization (unlike other projects such as coLinux) and makes direct use of the host file system (through VolFS and DrvFS)[40] and some parts of the hardware, such as the network, which guarantees interoperability. Web servers for example, can be accessed through the same interfaces and IP addresses configured on the host, and shares the same restrictions on the use of ports that require administrative permissions, or ports already occupied by other applications.[41] There are certain locations (such as system folders) and configurations whose access/modification is restricted, even when running as root, with sudo from the shell. An instance with elevated privileges must be launched in order to get «sudo» to give real root privileges, and allow such access.[22]

WSL 1 is not capable of running all Linux software, such as 32-bit binaries,[42][43] or those that require specific Linux kernel services not implemented in WSL. Due to a lack of any «real» Linux kernel in WSL 1, kernel modules, such as device drivers, cannot be run. WSL 2, however, makes use of live virtualized Linux kernel instances. It is possible to run some graphical (GUI) applications (such as Mozilla Firefox) by installing an X11 server within the Windows (host) environment (such as VcXsrv or Xming),[44] although not without caveats, such as the lack of audio support (though this can be remedied by installing PulseAudio in Windows in a similar manner to X11) or hardware acceleration (resulting in poor graphics performance). Support for OpenCL and CUDA is also not being implemented currently, although planned for future releases.[45][46] Microsoft stated WSL was designed for the development of applications, and not for desktop computers or production servers, recommending the use of virtual machines (Hyper-V), Kubernetes, and Azure for those purposes.[22]

In benchmarks WSL 1’s performance is often near native Linux Ubuntu, Debian, Intel Clear Linux or other Linux distributions. I/O is in some tests a bottleneck for WSL.[47][48][49] The redesigned WSL 2 backend is claimed by Microsoft to offer twenty-fold increases in speed on certain operations compared to that of WSL 1.[6] In June 2020, a benchmark with 173 tests with an AMD Threadripper 3970x shows good performance with WSL 2 (20H2) with 87% of the performance of native Ubuntu 20.04.0 LTS. This is an improvement over WSL 1, which has only 70% of the performance of native Ubuntu in this comparison. WSL 2 improves I/O performance, providing a near-native level.[50]
A comparison of 69 tests with Intel i9 10900K in May 2020 shows nearly the same relative performance.[51] In December 2020, a benchmark with 43 tests with an AMD Ryzen 5900X shows good performance with WSL 2 (20H2) with 93% of the performance of native 20.04.1 LTS. This is an improvement over WSL 1, which has only 73% in this comparison.[52]

WSL 2[edit]

Synaptic package manager running on WSL

Version 2 introduces changes in the architecture. Microsoft has opted for virtualization through a highly optimized subset of Hyper-V features, in order to run the kernel and distributions (based upon the kernel), promising performance equivalent to WSL 1. For backward compatibility, developers don’t need to change anything in their published distributions. WSL 2 settings can be tweaked by the WSL global configuration, contained in an INI file named .wslconfig in the User Profile folder.[53][54]

The distribution installation resides inside an ext4-formatted filesystem inside a virtual disk, and the host file system is transparently accessible through the 9P protocol,[55] similarly to other virtual machine technologies like QEMU.[56] For the users, Microsoft promised up to 20 times the read/write performance of WSL 1.[5] From Windows an IFS network redirector is provided for Linux guest file access using the UNC path prefix of \\wsl$.

WSL 2 requires Windows 11,[57] or Windows 10 version 1903 or higher, with Build 18362 or higher, for x64 systems, and Version 2004 or higher, with Build 19041 or higher, for ARM64 systems.[8]

WSL 2 and Windows 11 are in good shape with 95% performance of native Ubuntu 20.04 LTS.[58]

See also[edit]

  • Azure Sphere
  • FreeBSD § OS compatibility layers
  • SmartOS § Virtualization
  • Windows Terminal
  • Xenix

References[edit]

  1. ^ «Release 1.2.5 · microsoft/WSL». GitHub. Retrieved 4 July 2023.
  2. ^ «Release 2.0.1 · microsoft/WSL». GitHub. Retrieved 27 September 2023.
  3. ^ Leeks, Stuart (2020). Windows Subsystem for Linux 2 (WSL 2) Tips, Tricks, and Techniques: Maximise Productivity of Your Windows 10 Development Machine with Custom Workflows and Configurations. Birmingham: Packt Publishing. pp. 18–19. ISBN 978-1-80056-352-0. OCLC 1202451000.
  4. ^ June 2021, Darren Allan 23 (23 June 2021). «Windows 11 could seamlessly run graphical Linux apps». TechRadar. Retrieved 29 June 2021.
  5. ^ a b c d Craig Loewen (6 May 2019). «Announcing WSL 2». Windows Command Line Tools For Developers.
  6. ^ a b c mscraigloewen. «About WSL 2». docs.microsoft.com.
  7. ^ «WSL 2 Post BUILD FAQ». Windows Command Line Tools For Developers. 14 May 2019.
  8. ^ a b craigloewen-msft (24 February 2022). «Install WSL on Windows 10». Microsoft.
  9. ^ Bright, Peter (6 April 2016). «Why Microsoft needed to make Windows run Linux software». Ars Technica. Condé Nast.
  10. ^ Aul, Gabe (6 April 2016). «Announcing Windows 10 Insider Preview Build 14316». Windows Experience Blog. Microsoft.
  11. ^ «Windows Subsystem for Linux Overview». Windows Subsystem for Linux. Retrieved 22 April 2018.
  12. ^ a b «What’s new in WSL in Windows 10 Fall Creators Update — Windows Command Line». Windows Command Line. 11 October 2017. Retrieved 15 October 2021.
  13. ^ Heath, Nick (20 September 2017). «Will Microsoft love Linux to death? Shuttleworth and Stallman on whether Windows 10 is free software’s friend». TechRepublic. Archived from the original on 1 December 2022. Retrieved 18 February 2022.
  14. ^ Microsoft Ignite (2 October 2018), OS internals: Technical deep-dive into operating system innovations — BRK3365, archived from the original on 9 November 2021, retrieved 7 May 2019
  15. ^ «WSL 2 will be generally available in Windows 10, version 2004 — Windows Command Line». Windows Command Line. 13 March 2020. Retrieved 15 October 2021.
  16. ^ «WSL 2 Support is coming to Windows 10 Versions 1903 and 1909 — Windows Command Line». Windows Command Line. 20 August 2020. Retrieved 15 October 2021.
  17. ^ «GPU accelerated ML training inside the Windows Subsystem for Linux — Windows Developer Blog». Windows Blog. 17 June 2020. Retrieved 16 October 2021.
  18. ^ a b «The Initial Preview of GUI app support is now available for the Windows Subsystem for Linux — Windows Command Line». Windows Command Line. 21 April 2021.
  19. ^ Foley, Mary Jo (21 April 2021). «New Windows 10 test build adds first preview of Linux GUI apps on WSL». ZDNet. Retrieved 23 April 2021.
  20. ^ a b Abrams, Lawrence (29 May 2021). «Hands on with WSLg: Running Linux GUI apps in Windows 10». Bleeping Computer. Retrieved 30 May 2021.
  21. ^ «A preview of WSL in the Microsoft Store is now available! — Windows Command Line». Windows Command Line. 11 October 2021. Retrieved 16 October 2021.
  22. ^ a b c d e «Frequently Asked Questions for WSL». Microsoft. Retrieved 13 November 2016.
  23. ^ Harsh, Mike (30 March 2016). «Run Bash on Ubuntu on Windows». Building Apps for Windows. Microsoft.
  24. ^ Finley, Klint (30 March 2016). «Why Microsoft Making Linux Apps Run on Windows Isn’t Crazy». Wired. Condé Nast.
  25. ^ Kirkland, Dustin (30 March 2016). «Ubuntu on Windows – The Ubuntu Userspace for Windows Developers». Ubuntu Insights. Canonical.
  26. ^ Hammons, Jack (9 April 2016). «Bash on Ubuntu on Windows». MSDN. Microsoft.
  27. ^ Get openSUSE Leap 42 — Microsoft Store
  28. ^ Get SUSE Linux Enterprise Server 12 — Microsoft Store
  29. ^ Yegulalp, Serdar (12 May 2017). «Windows Subsystem for Linux welcomes Suse and Fedora options». InfoWorld. Retrieved 16 September 2017.
  30. ^ «Debian GNU/Linux for WSL now available in the Windows Store». Windows Command Line Tools For Developers. Retrieved 7 March 2018.
  31. ^ «Kali Linux in the Windows App Store». Retrieved 9 March 2018.
  32. ^ Manage and configure Windows Subsystem for Linux
  33. ^ Windows Subsystem for Linux interoperability with Windows
  34. ^ Command Reference for Windows Subsystem for Linux
  35. ^ a b c Welcome to WSLg, Microsoft, 7 November 2021, retrieved 7 November 2021
  36. ^ Salter, Jim (7 October 2021). «The best part of Windows 11 is a revamped Windows Subsystem for Linux». Ars Technica. Retrieved 7 November 2021.
  37. ^ «Installing WSLg». GitHub. 27 April 2022. Retrieved 27 April 2022.
  38. ^ «Clarify Windows 10 vs 11 and build numbers (#485) · microsoft/wslg@5ddd8d2». GitHub. Retrieved 28 May 2022.
  39. ^ Jack Hammons (22 April 2016). «Windows Subsystem for Linux Overview». Windows Subsystem for Linux blog on MSDN.
  40. ^ Jack Hammons (15 June 2016). «WSL File System Support». Windows Subsystem for Linux blog on MSDN.
  41. ^ Jack Hammons (8 November 2016). «WSL Networking». Windows Subsystem for Linux blog on MSDN.
  42. ^ «Please enable WSL to run 32 bit ELF binaries». Windows Developer feedback (Microsoft/UserVoice). Archived from the original on 23 August 2019. Retrieved 21 January 2018.
  43. ^ «Support for 32-bit i386 ELF binaries». GitHub.
  44. ^ «Windows 10’s Bash shell can run graphical Linux applications with this trick». PC World. Retrieved 10 September 2018.
  45. ^ «GPU not accesssible for running tensorflow and installing CUDA · Issue #1788 · Microsoft/WSL». GitHub. Retrieved 10 September 2018.
  46. ^ «OpenCL & CUDA GPU support». Windows Developer feedback (Microsoft/UserVoice). 15 September 2016. Archived from the original on 7 July 2018. Retrieved 10 September 2018.
  47. ^ «Windows Subsystem for Linux». Phoronix.
  48. ^ Larabel, Michael (12 October 2018). «A Look At The Windows 10 October 2018 Update Performance With WSL». Phoronix.
  49. ^ Larabel, Michael (5 November 2018). «The WSL Improvements In The Windows 10 October 2018 Update». Phoronix.
  50. ^ Larabel, Michael (24 June 2020). «Ubuntu 20.04 vs. Windows 10 WSL/WSL2 Performance In 170+ Benchmarks». Phoronix.
  51. ^ Larabel, Michael (17 June 2020). «Windows 10 May 2020 Performance For WSL vs. WSL2». Phoronix.
  52. ^ Larabel, Michael (16 December 2020). «Windows Subsystem For Linux / WSL2 Performance With The AMD Ryzen 9 5900X». Phoronix.
  53. ^ Loewen, Craig (26 July 2019). «What’s new for WSL in Insiders Preview Build 18945». Microsoft devblog. Archived from the original on 26 July 2019. Retrieved 26 July 2019. In this new update we’ve added the ability to start using global config options for WSL. These options are targeted towards power users who want to further customize their WSL experience.
  54. ^ Hillis, Ben (25 July 2019). «MicrosoftDocs/WSL | Build 18947». GitHub. Archived from the original on 26 July 2019. Retrieved 26 July 2019.
  55. ^ «A Deep Dive Into How WSL Allows Windows to Access Linux Files». Windows Command Line Tools For Developers. 30 May 2019. Retrieved 24 June 2019.
  56. ^ Jujjuri, Venkateswararao; Van Hensbergen, Eric; Liguori, Anthony; Pulavarty, Badari (13–16 July 2010). «VirtFS—A virtualization aware File System pass-through» (PDF). Linux Symposium.
  57. ^ «Comparing WSL 1 and WSL 2». Microsoft Learn. 4 October 2022. Retrieved 18 October 2022.
  58. ^ Larabel, Michael (29 September 2021). «Windows 11 WSL2 Performance is Quite Competitive Against Ubuntu 20.04 LTS / Ubuntu 21.10». Phoronix.

Further reading[edit]

  • Barnes, Hayden (2021). Pro Windows Subsystem for Linux (WSL): Powerful Tools and Practices for Cross-Platform Development and Collaboration. Apress. ISBN 978-1484268728.
  • Leeks, Stuart (2020). Windows Subsystem for Linux 2 (WSL 2) Tips, Tricks, and Techniques: Maximise productivity of your Windows 10 development machine with custom workflows and configurations. Packt Publishing. ISBN 978-1800562448.
  • Singh, Prateek (2020). Learn Windows Subsystem for Linux: A Practical Guide for Developers and IT Professionals. Apress. ISBN 978-1484260371.

External links[edit]

  • WSL on Microsoft Learn
  • WSL on GitHub
  • WSL2-Linux-Kernel on GitHub
  • Brown, Pete (22 July 2016). «Fun with the Windows Subsystem for Linux». Windows Developer Blog. Microsoft.

1.2K
показов

1.9K
открытий

Сегодня покажу как поставить WSL (Windows Subsystem for Linux) на Windows 11

В этой статье вы узнаете:

  • Что такое WSL и для чего она нужна
  • Гайд по установке WSL
  • Настройка компилятора
  • Что делать, если WSL потребляет избыточное количество оперативной памяти

Что такое WSL и для чего она нужна

WSL (Windows Subsystem for Linux) — это среда выполнения Linux, предоставляемая операционной системой Windows. WSL позволяет запускать исполняемые файлы Linux напрямую в Windows без необходимости установки отдельной виртуальной машины или перезагрузки компьютера.

WSL обеспечивает совместимость с ядром Linux, что позволяет пользователям запускать большинство командной строки и приложений Linux непосредственно в Windows. Оно включает в себя поддержку большинства дистрибутивов Linux, таких как Ubuntu, Debian, Fedora и других, и предлагает доступ к огромному количеству программ и утилит, которые разработаны для Linux.

Теперь перейдём к гайду

Гайд по установке WSL

Открываем PowerShell или Terminal от имени администратора

Можно как угодно открыть эти программы, думаю, вы в курсе))

Вводим следующую команду: wsl —install

Нажимаем Enter

Ждём

Кстати говоря, по умолчанию устанавливается дистрибутив — Ubuntu

По завершении установки перезагружаем наш ПК.

Мне нравится Ubuntu, поэтому я не буду её менять, но если ты хочешь поменять дистрибутив, то вот ссылка на инструкцию.

Теперь после установки WSL необходимо создать учетную запись пользователя и пароль для установленного дистрибутива Linux (в моём случаи речь идёт про Ubuntu):

Придумай имя

Обрати внимание, что пароль при вводе не видно((

На случай, если что-то пошло не так на этапе создания учётной записи вот мини-туториал как это можно исправить.

Готово!

Важный нюанс: Windows не выполняет автоматическую установку обновлений или обновление дистрибутивов Linux. Это задача, выполнение которой большинство пользователей Linux предпочитают контролировать самостоятельно. Поэтому обновим нашу подсистему с помощью этой команды: sudo apt update && sudo apt upgrade

Я перешёл из PowerShell в Terminal, не пугайтесь, всё будет работать также))

Да, Y с большой буквы, это важно))

Настройка компилятора

Я использую WSL, чтобы компилировать программы на языке С, поэтому покажу команды для установки компилятора.

По очереди:

sudo apt-get update

sudo apt-get install cmake gcc clang gdb build-essential

sudo apt-get install valgrind

Первая есть

Да.

Вторая

И третья

Важный момент: Проверим, установился ли у нас компилятор, должен появится номер: gcc —version

Что делать, если WSL потребляет избыточное количество оперативной памяти

Бонусом, я покажу, как снизить потребление оперативной памяти нашей подсистемой:

Вот это не есть хорошо((

Есть два пути

Путь первый:
Открываем командную строку от администратора и вставить команду
wsl —shutdown, эта команда завершит процесс VmmemWSL.

Чтобы легко открыть командную строку можно зажать кнопки Win + X > пункт PowerShell (Администратор) > команда start cmd > нажимаем Enter.

Путь второй:
Можно также ограничить ресурсы Vmmem путем создания файла %UserProfile%\.wslconfig, внутри которого прописать:

[wsl2]
memory=2GB # Ограничиваем память для WSL2 VM.processors=5 # Ограничиваем количество процессов для WSL2 VM.

Чтобы создать файл с названием .wslconfig — нужно открыть блокнот Win + R > notepad > вставить содержимое > Сохранить как > в Тип файла указать Все файлы, после указать название и сохранить.

Text Document

Всё

Более чем в два раза))

Кстати говоря, в этом файлике можете попробовать поставить значение memory равное 1, может ещё меньше будет))

На этом у меня всё, надеюсь моя статья помогла тебе решить твою проблему))

Благодарю за прочтение!

Windows Subsystem for Linux (WSL) — подсистема ОС Windows 10, позволяющая разработчикам, тестировщикам запускать нативные приложения Linux, писать скрипты, выполнять команды непосредственно из Windows. В обновлённой Windows 10 (2004) появилась 2я версия WSL, в которой используется полноценное ядро Linux с возможностью запуска приложений и контейнеров Docker, реализована высокая скорость загрузки, небольшой объем потребляемых ресурсов, управление в фоновом режиме, обновление ядра. Таким образом вы сможете запускать ELF64 программы, которые могут получать доступ к файловой системе Windows без использования сторонних порто (таких как Cygwin).

Образ ядра Linux (версия ядра 4.19) в Windows 10 представляет собой легкую виртуальную машину, для запуска которой не нужно ставить полноценную роль Hyper-V. Системные вызовы Linux транслируются на лету в вызовы Windows без использования эмулятора (в отличии от WSL1).

Изначально компонент WSL отключен. Чтобы его включить, вам необходимо зайти в Пуск -> Панель управления -> Программы и компоненты -> Включение и отключение компонентов Windows (Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off), активировать галочку Подсистема Windows для Linux (Windows Subsystem for Linux), нажать кнопку ОК, и перезагрузить компьютер.

установка Windows Subsystem for LInux 2 версия в windows 10

Вы можете включить компоненты WSL в Windows 10 с помощью dism:

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

или PowerShell

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

В Windows Server 2004 Semi-Annual Channel (SAC) для установки компонента WSL используется командлет Install-WindowsFeature:

Install-WindowsFeature -Name Microsoft-Windows-Subsystem-Linux

После этого также необходимо перезагрузить компьютер.

В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V.

Теперь вам нужно выполнить обновление WSL до версии 2. Для этого требуется зайти на сайт https://docs.microsoft.com/ru-ru/windows/wsl/wsl2-kernel, скачать файл wsl_update_x64.msi, установить его. По завершении увидите картинку

windows subsyste for linux update setup

Чтобы сделать WSL2 архитектурой по умолчанию для новых дистрибутивов, в PowerShell выполните команду:

wsl --set-default-version 2

Далее вам необходимо открыть Microsoft Store, в поиске ввести слово “Linux”. В появившемся списке выберите нужный дистрибутив. Доступные Ubuntu, Debian, Kali Linux, Linux Cheatsheet, SUSE Linux Enterprise Server15, openSUSE Leap 15-1, Pengwin Enterprise, Fedora Remix for WSL или другие. В нашем примере мы будем использовать Ubuntu 20.04 LTS, нажмите кнопку Получить.

образы linux для wsl в microsoft store

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

Invoke-WebRequest https://aka.ms/wslubuntu2004 -OutFile ubuntu-2004.zip –UseBasicParsing

Распакуйте архив:

Expand-Archive -Path .\ubuntu-2004.zip

Запустите установку образа Linux с помощью файла Ubuntu.exe.

Также вы можете скачать образ в виде appx файла и установить его с помощью командлета Add-AppxPackage.

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

wsl --list –-verbose

wsl --list –-verbose список доступных образов linux

Если у вашей среды Linux указана версия 1, нужно изменить ее на WSL2 командой:

wsl --set-version Ubuntu-20.04 2

Файл жёсткого диска с образом виртуальной машины ОС Linux Ubuntu 20.04 будет располагаться в профиле пользователя: C:\Users\234\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc\LocalState.

После установки дистрибутива в стартовом меню появляется ярлык на него. Для запуска Ubuntu зайдите в меню Пуск, нажмите на соответствующем ярлыке и получите в отдельном окне полноценную командную оболочку Bash. Запускать WSL можно и с помощью команды wsl. При первом запуске образа в командной строке Bash вам будет предложено создать пользователя и пароль (которые не должны совпадать с учётной записью Windows). Чтобы выполнять команды с правами root, необходимо использовать дополнительный ключ (префикс) sudo. В WSL есть общие команды для Bash и CMD, и тут нужно не забывать, что система Linux чувствительна к регистру.

Вы можете выполнить Linux-команды из CMD. Для этого необходимо вначале указать “WSL”. Например, для просмотра списка файлов и папок в каталоге Windows, выполните:

wsl
ls /mnt
ls/mnt/c

запуск команд linux в windows
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”

команды linux

Также вы можете открыть проводник командой explorer.exe, калькулятор – calc.exe, блокнот – notepad.exe, paint – mspaint.exe, календарь – cal, погоду – curl wttr.in

запуск команд linux в windows 10 subsystem for linux

Ещё один пример взаимосвязи 2х систем – вы можете открыть в Windows файл из WSL-дистрибутива по сетевому пути. Для этого в CMD наберите путь к файлу:

notepad \\wsl$\Ubuntu-20.04\home\1122.txt

Из окна консоли вы можете обновить список пакетов в Ubuntu с помощью команд:

sudo apt-get update
sudo apt-get upgrade

После обновления Ubuntu папка …/LocalState будет занимать 1.5 Гб.

Из командной строки Linux можно не только просмотреть Windows-файлы и каталоги, но и получить к ним доступ. Чтобы удобнее копировать файлы, просматривать директории и их содержимое, установите файловый менеджер Midnight Commander с помощью команды

sudo apt-get install mc

Вы можете запустить Midnight Commander как в командной оболочке Bash, так и внутри CMD. На скриншоте ниже показано, что в двух панелях MC показывается список файлов с обеих ОС.

Midnight Commander в windows 10 wsl2

Можно отобрахить сетевые настройки (IP адрес) IP-адрес Linux-системы:

ip addr | grep eth0

запуск команд linux из windows

В WSL не предусмотрена работа приложений с графическим интерфейсом. Тем не менее вы можете попробовать их установить и использовать. Чтобы запускать графические приложения в Linux, нужно скачать и установить в Windows программу VcXsrv Windows X Server (https://sourceforge.net/projects/vcxsrv/).

VcXsrv Windows X Server

С помощью пакетного менеджера apt-get установим несколько графических программ: например, браузер, текстовый редактор или что-то ещё:

sudo apt-get install gedit
sudo apt-get install firefox
sudo apt-get install x11-app

Затем создайте файл в директории root:

cd /~
vim .bash_login

впишите строку

export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0

сохраните запись

Esc -> :wr -> :q

Теперь можете запустить графические программы Linux через WSL командами:

firefox

или

gedit

запуск браузера firefox через WSL 2 в Windows 10

запуск графического редактора gedit в WSL

Вы можете установить в Windows 10 несколько дистрибутивов Linux и запускать одновременно в разных окнах WSL. Вывести весь перечень установленных дистрибутивов можете с помощью команды:

wsl --list –all

чтобы завершить работу всех запущенных дистрибутивов и ядра WSL 2, выполните команду:

wsl --shutdown

  • Windows subsystem for linux installation guide for windows 10
  • Windows subsystem for android with amazon appstore скачать
  • Windows steady state windows 10
  • Windows subsystem for linux gui
  • Windows subsystem for android root